I have a requirement where I need to run a task for every 5 seconds, but only between specific times (like between 1:30 and 2:30 tomorrow).
I looked at celery, but a normal task cannot be executed repeatedly in celery and the periodic tasks cannot be dynamically scheduled.
I also looked at APScheduler, but that doesn't support running it as a 'daemon' and scheduling tasks from outside.
Any idea what I could use to make this happen?
Edit: Should have mentioned this earlier, I need to do this during a web request, like a background task.
If I understood your question right, Maybe like this ?
from time import sleep
from datetime import datetime
if 90 <= datetime.now().hour * 60 + datetime.now().minute <= 150:
# Do something
time.sleep(5)
I converted hour to minute to handle the time easier. So 90min is 1.30 and 150min is 2.30. (Considered AM)
And the time module make this run at 5 second intervals.
If you also need days, you can implement that easily by;
datetime.now().day
And you need to put this into a loop for the condition to be continuously tested. The sleep method I used will result in checking every 5 seconds.
As you added the code can't be blocking the process. Another way could be using division method. Something like;
While #condition:
if not datetime.now().second % 5:
# Process
But of course I must add that this is a bad solution given that it always runs. So I am sure using an appropriate library will be more helpful, which is not in my knowledge at the moment.
I think @Rockybilly's answer is pretty close if you would like an entirely python specific answer. However, you will need to wrap that in a:
While True:
#@Rockybilly's if statement
This is needed in order to repeat the process. You'd also like to incorporate something as seen here: delay a task until certain time
You would do this once outside of your specified range (2:31 for instance), and then sleep the script until 1:30 the next day. This will help to ensure it's not constantly running.
As people have commented, you can do this, in some capacity, using either CRON (Unix) or Task Scheduler (Windows)
--
Since you have edited your question, I will add a response to that edit here. Please see my comment below, in response to @Rockybilly, as this is something you may want to clarify.
You may want to look into the threading, multiprocessing, or the new asyncio modules if these need to run in parallel.
(Can't link Asyncio due to rep restraints)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With