In daily work, we often use tasks that need to be performed periodically. One way is to use Crond [1] of The Linux system combined with the command line. Another way is to use Python directly. The following is a list of common implementations of Python timed tasks. \

\

While True: + sleep(

The sleep(secs) function in the time module allows the currently executing thread to pause for secs before resuming execution. The so-called pause means that the current thread enters the blocked state, and when it reaches the time specified by sleep(), it changes from the blocked state to the ready state, waiting for CPU scheduling.

With this feature we can implement simple timed tasks through a while loop +sleep().

Code examples:

import datetime import time def time_printer(): now = datetime.datetime.now() ts = now.strftime('%Y-%m-%d %H:%M:%S') print('do func time :', ts) def loop_monitor(): While True: time_printer() time.sleep(5) # pause 5 seconds if __name__ == "__main__": loop_monitor()Copy the code

Main disadvantages:

  • You can only set an interval, but cannot specify a specific time, such as 8:00 a.m. every day
  • Sleep is a blocking function, which means that during sleep, nothing can be done.

2. Use the Timeloop library to run scheduled tasks

Timeloop[2] is a library for running multi-cycle tasks. This is a simple library that uses the decorator pattern to run tag functions in a thread.

Sample code:

import time

from timeloop import Timeloop

from datetime import timedelta

tl = Timeloop()

@tl.job(interval=timedelta(seconds=2))

def sample_job_every_2s():

    print "2s job current time : {}".format(time.ctime())

@tl.job(interval=timedelta(seconds=5))

def sample_job_every_5s():

    print "5s job current time : {}".format(time.ctime())

@tl.job(interval=timedelta(seconds=10))

def sample_job_every_10s():

    print "10s job current time : {}".format(time.ctime())
Copy the code

3. Implement timed tasks using threading.Timer

The Timer in the threading module is a non-blocking function, which is a little bit better than sleep. A Timer is basically a Timer. We can start multiple timed tasks, and these Timer tasks are executed asynchronously, so there is no problem of waiting for sequential execution.

Timer(interval, function, args=[ ], kwargs={ })

  • Interval: specifies the time
  • Function: the method to execute
  • Args /kwargs: method parameters

Code examples:

import datetime

from threading import Timer

def time_printer():

    now = datetime.datetime.now()

    ts = now.strftime('%Y-%m-%d %H:%M:%S')

    print('do func time :', ts)

    loop_monitor()

def loop_monitor():

    t = Timer(5, time_printer)

    t.start()

if __name__ == "__main__":

    loop_monitor()
Copy the code

Note: Timer can only be executed once, so it needs to be called in a loop. Otherwise, Timer can only be executed once

4. Use the built-in module Sched to achieve scheduled tasks

The Sched module implements a generic event scheduler that uses a delay function in the scheduler class to wait for a specific time to execute the task. Multithreaded applications are also supported, and the delay function will be called immediately after each task is executed to ensure that other threads can also execute.

Class Sched. scheduler(timefunc, delayfunc) This class defines a generic interface for scheduling events. Timefunc is a function that returns a number of the time type without arguments. Delayfunc should be a function that takes one argument, is compatible with the output of timeFunc, and functions to delay multiple time units (commonly used, such as sleep for the Time module).

Code examples:

import datetime import time import sched def time_printer(): now = datetime.datetime.now() ts = now.strftime('%Y-%m-%d %H:%M:%S') print('do func time :', ts) loop_monitor() def loop_monitor(): Scheduler (time.time, time.sleep) # scheduler(5, 1, time_printer, ()) s.run() if __name__ == "__main__": loop_monitor()Copy the code

Scheduler object main methods:

  • Enter (delay, priority, action, argument) to schedule an event to delay delay units of time.
  • Cancel (event) : Deletes the event from the queue. If the event is not in the current queue, the method will run a ValueError.
  • Run () : Runs all scheduled events. This function will wait (using the delayfunc() function passed to the constructor) and then execute the event until there are no more scheduled events.

Better than threading.Timer, no loop required. \

Python is a very diverse and well-developed language, so there are definitely a lot of features THAT I haven’t considered, so if you know of any, let me know in the comments section