简体   繁体   English

Python:如何自动化脚本在特定时间每天运行?

[英]Python: How to automate script to run every day at specific time?

Currently, I have a python script that only starts once it hits the specified date/time, and never runs again unless I re-specify the date/time:目前,我有一个 python 脚本,它只有在到达指定的日期/时间后才会启动,除非我重新指定日期/时间,否则永远不会再次运行:

import datetime, time

start_time = datetime.datetime(2017, 4, 27, 19, 0, 0)

while(True):
    dtn = datetime.datetime.now()

    if dtn >= start_time:
       # Runs the main code once it hits the start_time

But how can I go about making it so that it only runs the code at a specified time, everyday?但是我怎样才能让它每天只在指定的时间运行代码呢?

Thank you in advance and will be sure to upvote/accept answer预先感谢您,并一定会赞成/接受答案

cronjob is the correct tool for this job. cronjob是这项工作的正确工具。
To create a job on a mac that executes every day at 12:00, open the terminal and type:要在每天 12:00 执行的mac上创建job ,请打开终端并键入:

env EDITOR=nano crontab -e
0 12 * * *  /full/path/to/python /full/path/to/script.py

CTRL+O and CTRL+X to save and exit. CTRL+OCTRL+X保存并退出。


Notes:笔记:

1 - A job is specified in the following format: 1 - job按以下格式指定:

在此处输入图片说明

2 - To see a list of your active crontab jobs, use the following command: 2 - 要查看活动crontab作业的列表,请使用以下命令:

crontab -l

Tips:提示:

Execute on workdays 1AM:在工作日凌晨 1 点执行:

0 1 * * 1-5 /full/path/to/python /full/path/to/script.py

Execute every 10 minutes:每 10 分钟执行一次:

*/10 * * * * /full/path/to/python /full/path/to/script.py

Log output to file:日志输出到文件:

*/10 * * * * /full/path/to/python /full/path/to/script.py >> /var/log/script_output.log 2>&1

Note:笔记:

Once you determine that the current time has exceeded the start time, increment the start time by the desired interval using a datetime.timedelta object.一旦您确定当前时间已超过开始时间,请使用datetime.timedelta对象将开始时间增加所需的间隔。

import datetime
import time

next_start = datetime.datetime(2017, 4, 27, 19, 0, 0)
while True:
    dtn = datetime.datetime.now()

    if dtn >= next_start:
        next_start += datetime.timedelta(1)  # 1 day
        # do what needs to be done

    time.sleep(AN_APPROPRIATE_TIME)

Using Python module apscheduler could be an option.使用 Python 模块 apscheduler 可能是一种选择。

from datetime import datetime
import time
import os

from apscheduler.schedulers.background import BackgroundScheduler


def tick():
    print('Tick! The time is: %s' % datetime.now())


if __name__ == '__main__':
    scheduler = BackgroundScheduler()
    scheduler.add_job(tick, 'interval', seconds=3)
    scheduler.start()
    print('Press Ctrl+{0} to exit'.format('Break' if os.name == 'nt' else 'C'))

    try:
        # This is here to simulate application activity (which keeps the main thread alive).
        while True:
            time.sleep(2)
    except (KeyboardInterrupt, SystemExit):
        # Not strictly necessary if daemonic mode is enabled but should be done if possible
        scheduler.shutdown()

Using a python you could try使用 python 你可以尝试

in both cases python interpreter must run and may possibly do other stuff while waiting for the right time.在这两种情况下,python 解释器都必须运行,并且在等待合适的时间时可能会做其他事情。

Or as suggested in the comment, you could use other service running on your os for scheduling your python script execution.或者按照评论中的建议,您可以使用在您的操作系统上运行的其他服务来安排您的 python 脚本执行。

Why not a cronjob (linux) or Task Scheduler ( windows)?为什么不是 cronjob (linux) 或 Task Scheduler (windows)? – Pedro Lobito — 佩德罗·洛比托

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

相关问题 如何安排python脚本在特定时间每天运行? (Windows计划除外) - How can I Schedule python script to run every day at specific time ? (except Windows schedule) 如何每天在特定时间运行python函数 - How to run a python function every day at specific time 如何在python每天特定时间运行一个function? - How to run a function every day at a specific time in python? 如何在 GCP 中每天运行 Python 脚本? - How to run a Python script every day in GCP? 如何安排脚本每天运行 Python - How to schedule a script to run every day for Python 在 Heroku 上部署时,每天在特定时间运行函数的 Python 脚本不起作用 - Python script to run a function at a specific time every day does not work when deployed on Heroku 每次完成后,如何自动运行我的 python 脚本以再次运行? - How can I automate my python script to run again after every time it finished? Python脚本每月在特定时间和日期发送邮件 - Python script to send mail at specific time and day every month time.sleep 是每天运行 python 脚本的好方法吗? - Is time.sleep a good way to run a python script every day? 如何在任何地方使用像python这样的免费在线服务器每天同时运行python脚本? - How to use free online servers like python anywhere to run python script at the same time every day?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM