gpt4 book ai didi

python - 安排代码稍后执行

转载 作者:行者123 更新时间:2023-12-04 14:27:59 25 4
gpt4 key购买 nike

我如何安排一些代码在以后的特定时间执行?

我试过:

import time
import datetime

time.sleep(420)
print(datetime.datetime.now())

但如果 Mac 进入休眠状态,这将不起作用。

为了澄清,我需要一个脚本(好吧,一些 python 函数,我可以将其放入单独的脚本中)以在将来的精确时间运行。

time.sleep 不满足我的需求,因为如果计算机在 time.sleep 超时期间休​​眠,那么实时延迟比传递给 time.sleep。例如,我在 12:00 使用 time.sleep 开始延迟 7 分钟。然后我合上我的 macbook 盖子。 12点07分打开,超时还没结束。事实上,我必须等到大约 12:13 才能完成超时,尽管最初我希望脚本的其余部分在 12:07 继续。

因此,我不需要它在计算机休眠时运行,而是计算机休眠不应该影响它运行的时间。

最佳答案

您最好的选择是使用 cron 或 Apple 的 launchd。由于您希望在从 sleep 中醒来后以设定的时间间隔无延迟地执行任何操作,这就是我的建议。

Cron 方法

要设置一个新的 cron 作业,您可以打开终端并使用时间信息和您想要执行的脚本(例如,每 7 分钟)对其进行编辑:

$ crontab -e

*/7 * * * * /usr/bin/python /path/to/myscript.py

以下是对含义的快速分解:

* * * * *  command to execute
│ │ │ │ │
│ │ │ │ └─── day of week (0 - 6) (0 to 6 are Sunday to Saturday, or use names; 7 is Sunday, the same as 0)
│ │ │ └──────── month (1 - 12)
│ │ └───────────── day of month (1 - 31)
│ └────────────────── hour (0 - 23)
└─────────────────────── min (0 - 59)

列出您在 crontab 中设置的作业:

$ crontab -l

使用 launchd 的定时作业

Apple 的建议是不要使用 crontab,而是使用 launchd。基本上这需要创建一个首选项列表,其中包含有关您的任务以及运行时间等的信息。

$ cd $HOME/Library/LaunchAgents
$ nano com.username.mytask.plist

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"
"http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>com.username.mytask</string>
<key>ProgramArguments</key>
<array>
<string>/path/to/myscript.sh</string>
</array>
<key>StartInterval</key>
<integer>7</integer>
<key>RunAtLoad</key>
<true/>
</dict>
</plist>

在 nano 中按 Control + O 然后按 Control + X 保存。

$ chmod +x /path/to/myscript.sh
$ launchctl load com.username.mytask.plist
$ launchctl start com.username.mytask.plist

以下将使您的脚本可执行,然后加载并启动启动代理。

停止和卸载:

$ launchctl stop com.username.mytask.plist
$ launchctl unload com.username.mytask.plist

更多信息:

Scheduling Timed JobsCreating a launchd Property List File

sleep 和关机的影响

If the system is turned off or asleep, cron jobs do not execute; they will not run until the next designated time occurs.

If you schedule a launchd job by setting the StartCalendarInterval key and the computer is asleep when the job should have run, your job will run when the computer wakes up. However, if the machine is off when the job should have run, the job does not execute until the next designated time occurs.

All other launchd jobs are skipped when the computer is turned off or asleep; they will not run until the next designated time occurs.

Consequently, if the computer is always off at the job’s scheduled time, both cron jobs and launchd jobs never run. For example, if you always turn your computer off at night, a job scheduled to run at 1 A.M. will never be run.

关于python - 安排代码稍后执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41411001/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com