An example of django using django apscheduler to implement timing tasks

  • 2021-07-24 11:17:10
  • OfStack

Download:

pip install apscheduler

pip install django-apscheduler

Add django-apscheduler to INSTALLED_APPS of settings in the project


INSTALLED_APPS = [

  ....

  'django_apscheduler',

]

Then after migrating the files,


./manage.py migrate

Generate two tables: django_apscheduler_djangojob and django_apscheduler_djangojobexecution

These two tables are used to manage the scheduled tasks you need, and then start writing the tasks you need to implement under any 1view:


 Start asynchronous timing task 
 import time
 from apscheduler.schedulers.background import BackgroundScheduler
 from django_apscheduler.jobstores import DjangoJobStore, register_events, register_job
 try: 
    #  Instantiate scheduler 
    scheduler = BackgroundScheduler()
    #  Scheduler uses DjangoJobStore()
    scheduler.add_jobstore(DjangoJobStore(), "default")
    # 'cron' Mode cycle, week 1 To the week 5 , every day 9:30:10 Execute ,id For work ID As a mark 
    # ('scheduler',"interval", seconds=1) # Use interval Mode loop, every 1 Second execution 1 Times 
    @register_job(scheduler, 'cron', day_of_week='mon-fri', hour='9', minute='30', second='10',id='task_time')
    def test_job():
      t_now = time.localtime()
      print(t_now)
 
   #  Monitoring task 
   register_events(scheduler)
   #  Scheduler starts 
   scheduler.start()
except Exception as e:
  print(e)
  #  If an error is reported, the scheduler will stop executing 
  scheduler.shutdown()

Related articles: