APScheduler -- Python Cron and apschedulercron
APScheduler is full of Advanced Python Scheduler and is a lightweight Python task scheduling framework. It allows you to schedule scheduled tasks like Cron and supports Python functions or any callable objects.
Install APScheduler
You can use pip tool to install:
Pip install apscheduler
Or download the latest source code package (https://pypi.python.org/pypi/APScheduler/) on Pypi for installation:
Python setup. py install
Simple Application (translated from official documents)
Start Scheduler with default configuration
from apscheduler.scheduler import Scheduler sched = Scheduler()sched.start()
from
apscheduler.scheduler
import
Scheduler
sched
=
Scheduler()
sched.start()
1. fixed-time scheduling:
From datetime import datefrom apschedrom. scheduler import Scheduler # Start Schedulersched = Scheduler () sched. start () # define the function def my_job (text) to be automatically scheduled: print text # define the task execution time (May 17, 2013) exec_date = date (2013, 5, 17) # add to the task queue and assign it to the variable to cancel other operations such as job = sched. add_date_job (my_job, exec_date, ['text'])
2. Periodic tasks:
Def job_function (): print "Hello World" # job_function will execute sched every two hours. add_interval_job (job_function, hours = 2) # It is the same as the preceding task, but it is required that sched be run only after, January 17. add_interval_job (job_function, hours = 2, start_date = '2017-5-17 ')
Decorator version:
@sched.interval_schedule(hours=2)def job_function(): print "Hello World"
3. Cron-style task scheduling:
Def job_function (): print "Hello World" # Schedule the job_function to run sched at, and on the third Friday of May, and, respectively. add_cron_job (job_function, month = '6-8-12 ', day = '3rd fri', hour = '0-3 ')
Decorator version:
@sched.cron_schedule(day='last sun')def some_decorated_task(): print "I am printed at 00:00:00 on the last Sunday of every month!"
For more powerful usage methods, refer to the official documentation.