crontab
是 Linux 系统中用于设置周期性被执行的任务的工具。通过 crontab
,用户可以安排任务在指定的时间或按照特定的时间间隔自动执行。
crontab
文件指定的任务。crontab
文件。/etc/crontab
或 /etc/cron.d/
目录下,用于执行系统级的任务。crontab -l
crontab -e
crontab -r
* * * * * /path/to/command arg1 arg2
| | | | |
| | | | ----- Day of week (0 - 7) (Sunday=0 or 7)
| | | ------- Month (1 - 12)
| | --------- Day of month (1 - 31)
| ----------- Hour (0 - 23)
------------- Minute (0 - 59)
例如,如果你想每天凌晨 2 点执行 /home/user/backup.sh
脚本,可以这样设置:
0 2 * * * /home/user/backup.sh
假设你有一个简单的 Bash 脚本 hello.sh
:
#!/bin/bash
echo "Hello, World!" >> /home/user/hello.log
给脚本添加执行权限:
chmod +x hello.sh
然后编辑 crontab 文件来定时运行这个脚本:
crontab -e
添加以下行来每分钟执行一次脚本:
* * * * * /home/user/hello.sh
保存并退出编辑器,你的任务现在应该会按计划执行了。
通过以上步骤,你应该能够成功地在 Linux 系统中使用 crontab
来安排和管理周期性任务。
领取专属 10元无门槛券
手把手带您无忧上云