加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

Python:实现计划任务和打包程序

发布时间:2020-12-20 11:01:04 所属栏目:Python 来源:网络整理
导读:Python==3.7.x 有两种方式实现计划任务: schedule APscheduler 打包python程序 定时器: schedule import schedule import time,datetime def task(name): print("{0}".format(name)) # 每隔2秒执行一次任务 schedule.every(2).seconds.do(task,name) # 每隔
Python==3.7.x

有两种方式实现计划任务:

  1. schedule
  2. APscheduler
  3. 打包python程序
  • 定时器:schedule
import schedule
  import time,datetime

  def task(name):
      print("{0}".format(name))

  # 每隔2秒执行一次任务
  schedule.every(2).seconds.do(task,name)
  # 每隔一小时执行一次任务
  schedule.every().hour.do(task,name)
  # 每天10:30执行一次任务
  schedule.every().day.at("10:30").do(task,name)

  while True:
      schedule.run_pending()
      # 因为schedule只是一个定时器,他不会死循环执行任务,所以我们这里需要使用while
      time.sleep(1)
  • 调度任务模块:apscheduler
# aps有两种方式写法

  ## 第一种(第一种写法)
  from apscheduler.schedulers.blocking import BlockingScheduler

  def task():
      print(‘task‘)

  aps = BlockingScheduler()
  #在6月,7月,8月,11月和12月的第三个星期五的00:00,01:00,02:00和03:00执行job_function
  aps.add_job(job_function,‘cron‘,month=‘6-8,11-12‘,day=‘3rd fri‘,hour=‘0-3‘)
  aps.start()

  ## 第二种(第二种写法,在某些情况下可以避免报错,比如将python程序打包成执行文件后,第一种方法写的就会报错(‘LookupError: No trigger by the name "cron" was found‘).)

  from apscheduler.schedulers.blocking import BlockingScheduler
  from apscheduler.triggers.interval import IntervalTrigger

  def task():
      print(‘task‘)

  # 每秒执行一次
  trigger = IntervalTrigger(seconds=1)
  aps = BlockingScheduler()
  aps.add_job(func=a._start,trigger=trigger)
  aps.start()
  • python程序打包命令

    pip install PyInstaller==3.5
    
    # 建议使用绝对路径
    pyinstaller main_handler.py -F -p <lib/site-packages path> -i <icon>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读