前面我介紹了使用uwsgi部署django項目,如今使用uwsgi來實現定時任務html
uwsgi實現定時任務的Python接口詳細請參考官方文檔python
把下面的代碼加入uwsgi的入口程序中,能夠寫到Django程序的wsgi.py裏面:web
import uwsgi # 將具體的cron job分到另外一個文件中寫,便於維護 from cron_job import * for job_id, job in enumerate(jobs): uwsgi.register_signal(job_id, "", job['name']) if len(job['time']) == 1: uwsgi.add_timer(job_id, job['time'][0]) else: uwsgi.add_cron(job_id, job['time'][0], job['time'][1], job['time'][2], job['time'][3], job['time'][4])
如下是cron_job.py,增長、刪除定時任務只須要修改這個Python腳本:django
import time def cron_print_time(signum): ISOTIMEFORMAT='%Y-%m-%d %X' print time.strftime(ISOTIMEFORMAT, time.localtime()) def cron_print_hello(signum): print "hello" jobs = [ { "name" : cron_print_time, "time": [0, 17, -1, -1, 1], #minute, hour, day, month, weekday, "-1" means "all",此例爲每一個週一的17:00 }, { "name" : cron_print_hello, "time": [2], #每隔2秒 }, ]