Is there a efficient way in Julia to pause execution of a program until the next day?

Viewed 343

Suppose I'm running a program and each day I want to pause the program after X iterations until the start of the next calendar day. The amount of time the program will have to be paused each day will vary because I do not know when X iterations will be completed on a given day.

Question Is there a simple way to pause the program so that it will restart at the start of the next day E.S.T?

I thought of using the sleep() function. The problem is the interval the program would have to pause each day is different so I can't put in an absolute time value. So I thought conceptually it would something like this might work.

while true 
    # run function until X loops
    # sleep(Minute(tomorrow's date - now())

But I'm not sure how I would get the start of tomorrow's date from Julia or if this is the most efficient approach.

Any thoughts would be greatly appreciated. Thanks!

2 Answers

Generally I'd recommend using some OS-level scheduler (like cron) for this instead of a long running process, but you can easily figure out the time your program needs to sleep with

julia> DateTime(today()) + Day(1) - now()
52522991 milliseconds

You would normally use cron like @pfitzseb said. However, the simplest nice Julia code could be:

function once_a_time(f, interval)
    repeat = Ref(true) 
    task = @async begin 
        sleep(5) # some calculated time to start
        while repeat[]
            @async f()
            sleep(interval)
        end
    end
    return (;task, repeat)
end

This function will execute f in given fixed intervals regardless of previous assumptions. This code uses green threads so it assumes that f execution time is smaller that the value of interval (or f is just mostly I/O). The function returns a handle to the task as well as reference to the repeat variable so you can stop your scheduler from an outside code.

Let us now test it:

julia> task, rep = once_a_time(()->println("hello ",round(Int,time()) % 1000), 5)
(task = Task (runnable) @0x000000001b69b850, repeat = Base.RefValue{Bool}(true))

julia> hello 347
hello 352
hello 357
hello 362
julia> rep[]=false
false
Related