python-Timer实现定时任务

概述

threading.Timer类可实现定时任务

感性认识

2秒后执行

  1. import threading,datetime
  2. def task():
  3. print(datetime.datetime.now())
  4. t=threading.Timer(2,task)
  5. t.start()

api说明

导入模块

  1. import threading

函数定义

  1. threading.Timer(interval, function, args=None, kwargs=None)
参数
  • interval:间隔秒数
  • function:执行的函数
  • args:给函数传递的参数
  • kwargs:给函数传递的关键字参数
返回

返回Timer对象

例子

2秒后执行任务

  1. import threading,datetime
  2. def task():
  3. print(datetime.datetime.now())
  4. timer = threading.Timer(2,task)
  5. timer.start()

每间隔1秒执行一次

  1. import threading,datetime
  2. def task():
  3. print(datetime.datetime.now())
  4. timer = threading.Timer(1,task)
  5. timer.start()
  6. task()

2秒钟后执行,并且之后间隔1秒执行一次

  1. import threading,datetime
  2. def task():
  3. print(datetime.datetime.now())
  4. timer = threading.Timer(1,task)
  5. timer.start()
  6. timer = threading.Timer(2,task)
  7. timer.start()

取消定时

  1. import threading,datetime
  2. def task():
  3. print(datetime.datetime.now())
  4. timer = threading.Timer(2,task)
  5. timer.start()
  6. timer.cancel() # 取消定时

原文出处:http://malaoshi.top/show_1EF3C1agfIFm.html