[{"createTime":1735734952000,"id":1,"img":"hwy_ms_500_252.jpeg","link":"https://activity.huaweicloud.com/cps.html?fromacct=261f35b6-af54-4511-a2ca-910fa15905d1&utm_source=V1g3MDY4NTY=&utm_medium=cps&utm_campaign=201905","name":"华为云秒杀","status":9,"txt":"华为云38元秒杀","type":1,"updateTime":1735747411000,"userId":3},{"createTime":1736173885000,"id":2,"img":"txy_480_300.png","link":"https://cloud.tencent.com/act/cps/redirect?redirect=1077&cps_key=edb15096bfff75effaaa8c8bb66138bd&from=console","name":"腾讯云秒杀","status":9,"txt":"腾讯云限量秒杀","type":1,"updateTime":1736173885000,"userId":3},{"createTime":1736177492000,"id":3,"img":"aly_251_140.png","link":"https://www.aliyun.com/minisite/goods?userCode=pwp8kmv3","memo":"","name":"阿里云","status":9,"txt":"阿里云2折起","type":1,"updateTime":1736177492000,"userId":3},{"createTime":1735660800000,"id":4,"img":"vultr_560_300.png","link":"https://www.vultr.com/?ref=9603742-8H","name":"Vultr","status":9,"txt":"Vultr送$100","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":5,"img":"jdy_663_320.jpg","link":"https://3.cn/2ay1-e5t","name":"京东云","status":9,"txt":"京东云特惠专区","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":6,"img":"new_ads.png","link":"https://www.iodraw.com/ads","name":"发布广告","status":9,"txt":"发布广告","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":7,"img":"yun_910_50.png","link":"https://activity.huaweicloud.com/discount_area_v5/index.html?fromacct=261f35b6-af54-4511-a2ca-910fa15905d1&utm_source=aXhpYW95YW5nOA===&utm_medium=cps&utm_campaign=201905","name":"底部","status":9,"txt":"高性能云服务器2折起","type":2,"updateTime":1735660800000,"userId":3}]
sched可用于定时任务,唯一需要注意的就是,这些任务在一个线程中运行,如果前面的任务耗时过长,则后面的任务将顺延执行。
但其使用方法还是很简单的,主要封装了一个类scheduler
import sched import time def printName(name): print(name,"@",time.time()) s =
sched.scheduler() s.enter(5,1,printName,("5 - 1",)) s.enter(5,2,printName,("5 -
2",)) s.enter(10,1,printName,("10 - 1",)) s.run()
其中,enter为s中添加事件,其前两个参数分别代表延时时长和任务执行顺序;printName为将要执行的函数,("5-1",)
为参数列表,表示第5s执行的第一个任务。
其执行结果如下
5 - 1 @ 1649725436.606954 5 - 2 @ 1649725436.6229577 10 - 1 @
1649725441.6388779
如果在函数中加一个延时,则后面的任务将顺延
def printName(name): print(name,"@",time.time()) time.sleep(6)
其输出结果为
5 - 1 @ 1649725617.7624931 5 - 2 @ 1649725623.7689147 10 - 1 @
1649725629.7827168
与enter相对的是cancel(evt)和empty,前者可以删除某个事件,后者可以清空所有事件。
如果配合thread使用,则可以解决sched阻塞的问题。
import sched import threading import time def printNameByThread(name):
threading.Thread(target=printName,args=[name]).start() s = sched.scheduler() s.
enter(5,1,printNameByThread,("5 - 1",)) s.enter(5,2,printNameByThread,("5 - 2",)
) s.enter(10,1,printNameByThread,("10 - 1",)) s.run()
其输出结果为
5 - 1 @ 1649725777.2276525 5 - 2 @ 1649725777.2276525 10 - 1 @
1649725782.2158542
所以,熟练使用thread和sched,就可以安排定时任务了。