yum install vixie-cron crontabs
apt-get install cron
* * * * *
分 时 日 月 星期
特别的
@yearly 0 0 1 1 * 每年运行一次
@monthly 0 0 1 * * 每月运行一次
@weekly 0 0 * * 0 每星期运行一次
@daily 0 0 * * * 每日运行一次
@hourly 0 * * * * 每小时运行一次
* * * * * 每分钟运行一次 这个就没有特殊的名称了
@reboot
将作业配置为在守护程序启动时运行一次。
由于 cron 通常永远不会重新启动,因此这通常用于系统启动时运行的任务
列出定时任务
crontab -l
编辑定时任务
crontab -e
和直接修改配置文件相比, crontab -e 在退出时会检测一次语法
crond.service
systemctl status crond.service
* * * * * cron.sh
#!/bin/bash
step=1 #间隔的秒数,不能大于60
for (( i = 0; i < 60; i=(i+step) )); do
$(php test.php)
sleep $step
done
exit 0
要使用文件锁确保当前只有一个脚本在运行
flock命令
例子1
```
#!/usr/bin/env bash
LOCK_FILE=/var/lock/test.lock
exec 99>"$LOCK_FILE"
flock -n 99
if [ "$?" != 0 ]; then
echo "$0 already running"
exit 1
fi
#脚本要做的其他事情
```
例子2
```
#!/usr/bin/env bash
[ "${FLOCKER}" != "$0" ] && exec env FLOCKER="$0" flock -en "$0" "$0" "$@" || :
# 如果${FLOCKER}环境变量没有设置,则尝试将脚本本身加锁,如果加锁成功,则运行当前脚本,(并且带上原有的参数),否则的话静默退出。
#脚本要做的其他事情
[Unit]
Description=MyTimer
[Service]
ExecStart=/bin/bash /path/to/MyTimer.sh
systemctl start MyTimer.service
[Unit]
Description=Runs mytimer every hour
[Timer]
# 定时器
OnUnitActiveSec=1h
# 定时器触发的任务
Unit=mytimer.service
[Install]
# 开机启动时的依赖项,大多数情况下都是填这个
WantedBy=multi-user.target
systemctl enable MyTimer.timer
列出所有定时器
systemctl list-timers
systemctl 的命令也能直接用在 定时器中
start stop status enable disable
查看所有单元
systemctl list-unit-files
查看所有 Service 单元
systemctl list-unit-files --type service
查看所有 Timer 单元
systemctl list-unit-files --type timer
taskschd.msc
https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/schtasks
https://learn.microsoft.com/zh-cn/windows/win32/taskschd/task-scheduler-start-page
https://learn.microsoft.com/zh-cn/windows/win32/taskschd/using-the-task-scheduler
schtasks /Query
schtasks /Query /TN "\Microsoft\Windows\WwanSvc\NotificationTask"
schtasks /Query /V /TN "\Microsoft\Windows\WwanSvc\NotificationTask"
schtasks /Delete /TN taskname /F
taskname 是任务名
/F 是强制执行
schtasks /Create /TN taskname /TR taskrun
定时任务的表达式有一点混乱,最好还是去看文档
每分钟运行一次
schtasks /create /sc minute /mo 1 /tn "task name" /tr "command"
开机启动,设置开机启动的任务需要管理员权限
schtasks /create /sc ONSTART /tn "task name onstart" /tr "command"
https://learn.microsoft.com/en-us/powershell/module/scheduledtasks
https://learn.microsoft.com/zh-cn/powershell/module/microsoft.powershell.utility/new-timespan
$Act1 = New-ScheduledTaskAction -Execute "command";
$Time = New-ScheduledTaskTrigger -Once -At (Get-Date) -RepetitionInterval (New-TimeSpan -Minutes 1) ;
Register-ScheduledTask -TaskName "SoftwareScan" -Trigger $Time -Action $Act1;
每分钟运行一次
Register-ScheduledTask -TaskName "SoftwareScan" -Trigger (New-ScheduledTaskTrigger -Once -At (Get-Date) -RepetitionInterval (New-TimeSpan -Minutes 1)) -Action (New-ScheduledTaskAction -Execute "command");
开机启动
Register-ScheduledTask -TaskName "SoftwareScan" -Trigger (New-ScheduledTaskTrigger -AtStartup) -Action (New-ScheduledTaskAction -Execute "command");
每天11:00和23:00运行一次
$Act1 = New-ScheduledTaskAction -Execute "command";
$Time1 = New-ScheduledTaskTrigger -Daily -At 11am;
$Time2 = New-ScheduledTaskTrigger -Daily -At 11pm;
Register-ScheduledTask -TaskName "SoftwareScan2" -Trigger ($Time1, $Time2) -Action $Act1;
schtasks /create /sc minute /mo 1 /ru System /tn "acme_cron" /tr "command"
Register-ScheduledTask -User System -TaskName "SoftwareScan" -Trigger (New-ScheduledTaskTrigger -Once -At (Get-Date) -RepetitionInterval (New-TimeSpan -Minutes 1)) -Action (New-ScheduledTaskAction -Execute "command");
Register-ScheduledTask -Xml test.xml -TaskName "task name"
schtasks /create /xml test.xml /tn "task name"
wmic path Win32_OperatingSystem get LastBootUpTime
(get-date) - (gcim Win32_OperatingSystem).LastBootUpTime
(Get-Date (Get-CimInstance -ClassName win32_operatingsystem).LastBootUpTime -UFormat %s).ToString() // 开机时间的10位时间戳
锁定 注销 睡眠 休眠 都 不会计入停机时间
at 和 atq 通常用于一次性任务
powershell
# 睡眠 5 秒钟
[System.Threading.Thread]::Sleep(5000) ; echo cron
Start-Sleep -Seconds 5 ; echo cron
Start-Sleep -Milliseconds 5000 ; echo cron
bat
timeout /t 5 & echo cron
bash
sleep 5 ; echo cron
# 每30秒访问一次 http://127.0.0.1:80/mycron.php
<Proxy "balancer://mycron">
BalancerMember "http://127.0.0.1:80" hcmethod=GET hcuri=/mycron.php hcinterval=30
</Proxy>
<!-- 计划任务 schedule job 触发器 基于时间的 一次性任务 延时 指定日期 周期性任务 基于事件的 系统事件 开机/关机 用户登入/用户登出 系统状态 cpu 内存 硬盘io 网络io 自定义事件 web hook 这类的 任务 执行脚本 脚本库 任务监控 记录任务的状态 是否有出错,出错是否有错误的记录? 运行开始时间 运行时长 运行结束时间 失败后重试? 任务超时后强制关闭? 任务的miss? 失败后的日志和通知? 分布式的任务?distributed schedule job https://github.com/f2h2h1/php-win-cron 怎样实现一个 cron ? 定时任务相关的数据结构? 最小堆 powershell 模拟 CMD 的输出提示(例如:“等待 5 秒,按任意键继续...”) function Timeout($seconds) { Write-Host "等待 $seconds 秒,按任意键继续..." $start = Get-Date while ((Get-Date) - $start).TotalSeconds -lt $seconds) { if ($host.UI.RawUI.KeyAvailable) { $key = $host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown") break } Start-Sleep -Milliseconds 100 } } # 使用示例: Timeout 5 cron 在容器内运行 还是 在宿主机运行? 在容器中运行 supervisor https://github.com/aptible/supercronic/ 在容器中运行一个无限循环的 bash 使用容器的 healthcheck 在容器中运行 cron ,然后在前台运行 tail -f /var/log/cron.log https://blog.crackcreed.com/zai-dockerrong-qi-zhong-zhi-xing-ding-shi-ren-wu/ 在容器外运行 cron 和 docker exec 为什么 定时任务 做不到毫秒级? 因为 linux 和 windows 都不是 实时系统 -->