python3 定时器

版权声明:本文为博主原创文章,未经允许不得转发 https://blog.csdn.net/fengchen0123456789/article/details/83898734

环境搭建不多讲,如若linux环境有python2,python3
则为 python3 下载pip指令

sudo apt-get install python3-pip

下载这个还不行,还要执行如下命令

sudo apt-get install python3-setuptools

可能你下载包的时候还有问题,但LZ已经没有问题了
上面只是 ubuntu 安装pip指令,参考https://blog.csdn.net/cjeric/article/details/71104445,这个哥们遇到的问题还很多的,下面我们进入正题,

依赖包

我们这里使用的定时器依赖 apscheduler 库

下载apscheduler

pip3 install apscheduler

下载完之后可以执行 pip list 查看一下

代码

因为只是一个简单的实现,就不多说了,直接代码

from apscheduler.schedulers.blocking import BlockingScheduler 
from apscheduler.triggers.cron import CronTrigger
import time

def start_job(s): 
    print("start:"+time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())+s) 

def stop_job(): 

    print("end:"+time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))

def main(): 
    print("hello python")
    sched = BlockingScheduler() 
    # 每隔5妙执行一次 可以加入 id 参数,以方便结束该定时器  sched.remove("id")
    sched.add_job(start_job, 'cron', hour='*',minute="*",second="0/5",args=("hello",)) 
    # sched.add_job(start_job, CronTrigger.from_crontab('0/5 * * * *'))
    # 每隔3妙执行一次
    sched.add_job(stop_job, 'cron', hour='*',minute="*",second="0/3")
    # sched.add_job(stop_job, CronTrigger.from_crontab('0/3 * * * *'))
    # sched.add_job(stop_job, 'cron', day_of_week='0-4', hour='1-23',minute="0-59",second="2") 
    sched.start() 

if __name__ == '__main__': 
    main()

上面简单的传了一个参数,注意后面要跟个 ,号
参考 https://apscheduler.readthedocs.io/en/latest/modules/triggers/cron.html

执行

python3 /home/yf/soft/liu/vital_signs_data/test.py

猜你喜欢

转载自blog.csdn.net/fengchen0123456789/article/details/83898734
今日推荐