Python uses APScheduler for timed tasks

Keywords: Python Qt crontab pip

APScheduler is a Python timer task framework based on Quartz.Tasks based on dates, fixed intervals, and crontab types are provided and can be persisted.
Online documentation: https://apscheduler.readthedocs.io/en/latest/userguide.html

1. Install APScheduler

pip install apscheduler

2. Basic concepts

APScheduler has four components:
1. Trigger triggers:
Triggers contain scheduling logic.Each job has its own triggers that determine when the next task will run.Triggers are completely stateless except for the initial configuration.
There are three built-in trigger s:
(1) date: triggered at a specific point in time
(2) interval: fixed interval trigger
(3) cron: triggered periodically at a specific time
2. Task Store job stores: Store tasks in memory (default MemoryJobStore) or in a database.
3. Executor executors: An executor submits a task to a thread pool or a process pool to run, and when the task completes, the executor tells the scheduler to trigger the corresponding event.
4. Scheduler schedulers: Run by creating a dispatcher instance with the above three components as parameters
Select the appropriate components for your development needs. Here are the different scheduler components:
BlockingScheduler Blocking Scheduler: For programs that run only schedulers.
BackgroundScheduler Background Scheduler: For non-blocking scenarios, the scheduler runs independently in the background.
AsyncIO Scheduler AsyncIO Scheduler, suitable for applications that use AsyncIO.
The GeventScheduler Gevent Scheduler is designed for applications that pass through Gevent.
The Tornado Scheduler Tornado Scheduler is suitable for building Tornado applications.
TwistedScheduler Twisted Scheduler, suitable for building Twisted applications.
QtScheduler Qt Scheduler, suitable for building Qt applications.

3. Steps for use
1. Create a new scheduler
2. Add Scheduling Tasks
3. Run Scheduling Tasks

4. Examples of use

1. Trigger date

Triggers at a specific point in time and executes only once.The parameters are as follows:

parameter Explain
run_date (datetime or str) The date or time the job was run
timezone (datetime.tzinfo or str) Specify time zone

Example use:

from datetime import datetime
from datetime import date
from apscheduler.schedulers.blocking import BlockingScheduler

def job(text):    
    print(text)

scheduler = BlockingScheduler()
# In 2019-8-30 Run once job Method
scheduler.add_job(job, 'date', run_date=date(2019, 8, 30), args=['text1'])
# In 2019-8-30 01:00:00 Run once job Method
scheduler.add_job(job, 'date', run_date=datetime(2019, 8, 30, 1, 0, 0), args=['text2'])
# In 2019-8-30 01:00:01 Run once job Method
scheduler.add_job(job, 'date', run_date='2019-8-30 01:00:00', args=['text3'])

scheduler.start()

2. Trigger interval

Fixed interval trigger.The parameters are as follows:

parameter Explain
weeks (int) Weeks apart
days (int) A few days apart
hours (int) Hours apart
minutes (int) Minutes apart
seconds (int) How many seconds apart
start_date (datetime or str) Start date
end_date (datetime or str) End date
timezone (datetime.tzinfo or str)  

Example use:

import time
from apscheduler.schedulers.blocking import BlockingScheduler

def job(text):    
    t = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
    print('{} --- {}'.format(text, t))

scheduler = BlockingScheduler()
# Run every minute job Method
scheduler.add_job(job, 'interval', minutes=1, args=['job1'])
# In 2019-08-29 22:15:00 To 2019-08-29 22:17:00 Period, run every 1 minute 30 seconds job Method
scheduler.add_job(job, 'interval', minutes=1, seconds = 30, start_date='2019-08-29 22:15:00', end_date='2019-08-29 22:17:00', args=['job2'])

scheduler.start()

'''
//Run result:
job2 --- 2019-08-29 22:15:00
job1 --- 2019-08-29 22:15:46
job2 --- 2019-08-29 22:16:30
job1 --- 2019-08-29 22:16:46
job1 --- 2019-08-29 22:17:46
...Remaining omitted...
'''

3. Trigger cron

Triggers periodically at a specific time.The parameters are as follows:

parameter Explain
year (int or str) Year, 4 digits
month (int or str) Month (range 1-12)
day (int or str) Days (range 1-31)
week (int or str) Weeks (range 1-53)
day_of_week (int or str) The day or day of the week (range 0-6 or mon,tue,wed,thu,fri,sat,sun)
hour (int or str) Hour (range 0-23)
minute (int or str) Score (range 0-59)
second (int or str) Seconds (range 0-59)
start_date (datetime or str) Earliest start date (inclusive)
end_date (datetime or str) Latest end time (inclusive)
timezone (datetime.tzinfo or str) Specify time zone

These parameters support arithmetic expressions in the following formats:

Example use:

import time
from apscheduler.schedulers.blocking import BlockingScheduler

def job(text):    
    t = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
    print('{} --- {}'.format(text, t))

scheduler = BlockingScheduler()
# Run every minute at 22 o'clock a day job Method
scheduler.add_job(job, 'cron', hour=22, minute='*/1', args=['job1'])
# Run once a day at 22 and 23:25 job Method
scheduler.add_job(job, 'cron', hour='22-23', minute='25', args=['job2'])

scheduler.start()

'''
//Run result:
job1 --- 2019-08-29 22:25:00
job2 --- 2019-08-29 22:25:00
job1 --- 2019-08-29 22:26:00
job1 --- 2019-08-29 22:27:00
...Remaining omitted...
'''

4. Add method by decorator scheduled_job()

There are two ways to add tasks:

(1) By calling add_job() - see codes 1 to 3 above
(2) through the decorator scheduled_job():
The first is the most common method.The second method is primarily to conveniently declare tasks that will not change when the application is running.The add_job() method returns an apscheduler.job.Job instance that you can use to modify or delete the task later.

import time
from apscheduler.schedulers.blocking import BlockingScheduler

scheduler = BlockingScheduler()

@scheduler.scheduled_job('interval', seconds=5)
def job1():    
    t = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
    print('job1 --- {}'.format(t))

@scheduler.scheduled_job('cron', second='*/7')
def job2():    
    t = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
    print('job2 --- {}'.format(t))

scheduler.start()

'''
//Run result:
job2 --- 2019-08-29 22:36:35
job1 --- 2019-08-29 22:36:37
job2 --- 2019-08-29 22:36:42
job1 --- 2019-08-29 22:36:42
job1 --- 2019-08-29 22:36:47
job2 --- 2019-08-29 22:36:49
...Remaining omitted...
'''

Posted by Megalink on Thu, 29 Aug 2019 09:40:14 -0700