In python how to implement a thread which runs in the background (may be when the module loads) and calls the function every minute Monday to Friday 10 AM to 3 PM. For example the function should be called at:
10:01 AM 10:02 AM 10:03 AM . . 2:59 开发者_StackOverflowPM
Any pointers?
Environment: Django
Thanks
Django is a server application, which only reacts to external events.
You should use a scheduler like cron to create events that call your django application, either calling a management subcommand or doing an HTTP request on some special page.
The threading.Timer
class is convenient to do such tasks. But you have to compute interval yourself.
I think you can make a command http://docs.djangoproject.com/en/1.1/howto/custom-management-commands/#howto-custom-management-commands and then cron it.
Note sure how django affects threads (unless you're using App Engine where you can't do low level such), but once your thread is running you can continuously check timestamps:
from datetime import time
from datetime import date
time_delta = 60
while True:
end_time = time.time() + time_delta
while time.time() < end_time:
time.sleep(1)
if date.today().weekday() in range(1,5):
#do something baby
Not tested, so take it for a spin first.
Here is an article about scheduling tasks in cron from google code.
Scheduling Tasks with Cron
精彩评论