在Ubuntu系统中,你可以使用cron来定时运行Python脚本。以下是设置定时任务的步骤:
打开终端。
输入crontab -e命令来编辑当前用户的crontab文件。如果你需要以root用户身份运行脚本,请使用sudo crontab -e。
在打开的crontab文件中,你可以按照cron的时间格式添加一行来设置定时任务。Cron的时间格式如下:
* * * * * /usr/bin/python3 /path/to/your/script.py
- - - - -
| | | | |
| | | | ----- Day of the week (0 - 7) (Sunday to Saturday; 7 is also Sunday)
| | | ------- Month (1 - 12)
| | --------- Day of the month (1 - 31)
| ----------- Hour (0 - 23)
------------- Minute (0 - 59)
例如,如果你想要每天早上6点运行你的Python脚本,你可以添加以下行:
0 6 * * * /usr/bin/python3 /path/to/your/script.py
确保将/path/to/your/script.py替换为你的Python脚本的实际路径。
保存并关闭crontab文件。
为了确保cron服务正在运行并且你的任务已经设置好了,你可以重启cron服务:
sudo service cron restart
或者
sudo systemctl restart cron
现在,你的Python脚本将根据你设置的时间自动运行了。如果你想要查看你的cron任务列表,可以在终端中输入crontab -l命令。