简体   繁体   English

Python每天在定义的时间运行一段代码

[英]Python to run a piece of code at a defined time every day

In my python program, I would like it to run a piece of code at a pre-defined time every weekday, let say 2pm Mon - Fri.在我的 python 程序中,我希望它在每个工作日的预定义时间运行一段代码,比如周一至周五下午 2 点。

How may I do it please?请问我该怎么做?

You can use "schedule" library您可以使用“计划”库

to install, on terminal enter:安装,在终端输入:

pip install schedule

here is an example of the code you want:这是您想要的代码示例:

#!/usr/bin/python

import schedule
import time

def job():
    print("I am doing this job!")


schedule.every().monday.at("14:00").do(job)
schedule.every().tuesday.at("14:00").do(job)
schedule.every().wednesday.at("14:00").do(job)
schedule.every().thursday.at("14:00").do(job)
schedule.every().friday.at("14:00").do(job)

while True:
    schedule.run_pending()
    time.sleep(1)

or you can read the documents to see the other functions Click Here或者你可以阅读文档查看其他功能点击这里

good luck!祝你好运!

you can make use of crontab linux utility, Crontab (CRON TABle) is a file which contains the schedule of cron entries to be run and at specified times.您可以使用 crontab linux 实用程序,Crontab (CRON TABle) 是一个文件,其中包含要在指定时间运行的 cron 条目的时间表。

for your question , goto the python file's directory and enter in terminal对于您的问题,转到 python 文件的目录并在终端中输入

crontab -e

then within crontab file you can enter like this , for eecuting at 2.30pm daily然后在 crontab 文件中,您可以像这样输入,每天下午 2.30 开始执行

30 14 * * *         python3 your_python_file.py

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM