Detailed explanation of Python's timing module `APScheduler`: (You need to install the library first)

APSchedulerDetailed explanation of Python timing module : (need to install first)

		pip3 install apscheduler
  1. APScheduler is based on a Python timing task framework of Quartz, which implements all the functions of Quartz and is very convenient to use. Provides tasks based on dates, fixed time intervals, and crontab types , and can persist tasks. Based on these functions, we can easily implement a python timing task system.
  2. The four components of APScheduler:
  1. **Trigger** contains scheduling logic. Each job has its own trigger to determine which job will run next. Except for their own initial configuration accidents, triggers are completely stateless.
  2. **Job store** stores scheduled jobs. The default job store simply saves the job in the memory, and other job stores save the job in the database. The data of a job is serialized when it is saved in the persistent job storage, and deserialized when it is loaded. The scheduler cannot share the same job storage.
  3. The **executor** handles the running of the job, and they usually do it by submitting the specified callable object to a thread or entering the city in the job. When the job is completed, the executor will notify the scheduler.
  4. **Scheduler** is the other component. You usually have only one scheduler in your application, and the application developer usually does not directly deal with job storage, schedulers, and triggers. On the contrary, the scheduler provides a suitable interface to handle these. Configuring job storage and executors can be done in the scheduler, such as adding, modifying and removing jobs.
  1. Simple application:

    import time
    from apscheduler.schedulers.blocking import BlockingScheduler
     
    def my_job():
        print time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
     
    sched = BlockingScheduler()
    sched.add_job(my_job, 'interval', seconds=5)
    sched.start()
    

    The above example means that the my_job function is executed every 5s, and the current time information is output

  2. Operational job

    1. Add assignment

      The above is to add a job through add_job(), and another way is to modify the function through the scheduled_job() modifier

      import time
      from apscheduler.schedulers.blocking import BlockingScheduler
      
      sched = BlockingScheduler()
      
      @sched.scheduled_job('interval', seconds = 5)
      def my_job():
          print time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))    
      sched.start()
      
    2. Remove job

      job = scheduler.add_job(myfunc, 'intercal', minutes = 2)
      job.remove()
      #如果有多个任务序列的话可以给每个任务设置ID号,可以根据ID号选择清除对象,且remove放到start前才会有效
      sched.add_job(myfunc, 'interval', minutes = 2, id = 'my_job_id')
      sched.remove_job('my_job_id')
      
    3. Pause and resume operations

      1. Pause the job:

        apsched.job.Job.pause()
        apsched.schedulers.base.BaseScheduler.pause_job()
        
      2. Recovery job:

        apsched.job.Job.resume()
        apsched.schedulers.base.BaseScheduler.resume_job()
        
    4. Get job list

      Get a list of scheduled jobs, which can be used get_jobs()to complete, and it will return all job instances. Or use print_jobs()to output a list of all formatted jobs. You can also use get_job (task ID) to get the job list of the specified task

      job = sched.add_job(my_job, 'interval', seconds=2 ,id='123')
      print sched.get_job(job_id='123')
      print sched.get_jobs()
      
    5. Close scheduler

      By default, the scheduler will wait for the completion of all running jobs and close all schedulers and job storage. If you don't want to wait, you can set the wait option to False.

      sched.shutdown()
      sched.shutdown(wait=False)
      
  3. Control of job operation (trigger)

    The second parameter of add_job is trigger, which manages how the job is scheduled. It can be date, interval or cron. For different triggers, the corresponding parameters are also the same.

    1. cron timing scheduling (executed at a certain time)

      (int|str) 表示参数既可以是int类型,也可以是str类型
      (datetime | str) 表示参数既可以是datetime类型,也可以是str类型
       
      year (int|str)4-digit year -(表示四位数的年份,如2008年)
      month (int|str) – month (1-12) -(表示取值范围为1-12月)
      day (int|str) – day of the (1-31) -(表示取值范围为1-31日)
      week (int|str) – ISO week (1-53) -(格里历20061231日可以写成2006-W52-7(扩展形式)或2006W527(紧凑形式))
      day_of_week (int|str) – number or name of weekday (0-6 or mon,tue,wed,thu,fri,sat,sun) - (表示一周中的第几天,既可以用0-6表示也可以用其英语缩写表示)
      hour (int|str) – hour (0-23) - (表示取值范围为0-23时)
      minute (int|str) – minute (0-59) - (表示取值范围为0-59分)
      second (int|str) – second (0-59) - (表示取值范围为0-59秒)
      start_date (datetime|str) – earliest possible date/time to trigger on (inclusive) - (表示开始时间)
      end_date (datetime|str) – latest possible date/time to trigger on (inclusive) - (表示结束时间)
      timezone (datetime.tzinfo|str) – time zone to use for the date/time calculations (defaults to scheduler timezone) -(表示时区取值)
      
      ####例子:
      #表示2017年3月22日17时19分07秒执行该程序
      sched.add_job(my_job, 'cron', year=2017,month = 03,day = 22,hour = 17,minute = 19,second = 07)
       
      #表示任务在6,7,8,11,12月份的第三个星期五的00:00,01:00,02:00,03:00 执行该程序
      sched.add_job(my_job, 'cron', month='6-8,11-12', day='3rd fri', hour='0-3')
       
      #表示从星期一到星期五5:30(AM)直到2014-05-30 00:00:00
      sched.add_job(my_job(), 'cron', day_of_week='mon-fri', hour=5, minute=30,end_date='2014-05-30')
       
      #表示每5秒执行该程序一次,相当于interval 间隔调度中seconds = 5
      sched.add_job(my_job, 'cron',second = '*/5')
      
      
    2. Interval interval scheduling (how often to execute)

      weeks (int) – number of weeks to wait
      days (int) – number of days to wait
      hours (int) – number of hours to wait
      minutes (int) – number of minutes to wait
      seconds (int) – number of seconds to wait
      start_date (datetime|str) – starting point for the interval calculation
      end_date (datetime|str) – latest possible date/time to trigger on
      timezone (datetime.tzinfo|str) – time zone to use for the date/time calculations
      
      ###例子
      #表示每隔3天17时19分07秒执行一次任务
      sched.add_job(my_job, 'interval',days  = 3,hours = 17,minutes = 19,seconds = 7)
      
    3. Date scheduled scheduling (job will only be executed once)

      run_date (datetime|str) – the date/time to run the job at  -(任务开始的时间)
      timezone (datetime.tzinfo|str) – time zone for run_date if it doesn’t have one already
      
      ###例子
      # The job will be executed on November 6th, 2009
      sched.add_job(my_job, 'date', run_date=date(2009, 11, 6), args=['text'])
      # The job will be executed on November 6th, 2009 at 16:30:05
      sched.add_job(my_job, 'date', run_date=datetime(2009, 11, 6, 16, 30, 5), args=['text'])
      

Guess you like

Origin blog.csdn.net/qq_40596572/article/details/104413604