Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run a task in python for regular intervals between certain times? [duplicate]

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.

like image 811
Scaraffe Avatar asked May 25 '26 22:05

Scaraffe


2 Answers

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.

like image 69
Rockybilly Avatar answered May 28 '26 13:05

Rockybilly


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)

like image 44
disflux Avatar answered May 28 '26 14:05

disflux