浏览 AI使用教程
定时任务怎么设置:写清输入、失败通知、重试和停止条件
定时任务需要的不只是执行时间。输入来源、幂等、最大重试、失败通知和停止条件缺一项,都可能让一次小故障变成持续外部影响。
按实际操作顺序推进
每完成一段就检查当前输出,确认结果符合预期后再继续。
凌晨任务每分钟重试,为什么早上才发现限额耗尽
每天09:00整理前一天的一份文本输入。输入迟到时有限等待,失败后写暂停标记,并向已登录用户弹出提示,等待人工处理。
下面任务需读者在自己的 Windows 测试目录注册,本文未替读者创建系统任务。交互通知只适用于用户保持登录,不能充当无人值守服务器告警。
- 注册的是操作系统持久任务
- 失败产生暂停标记与可查日志
- 人工恢复前核对批次和已有输出
动手前,把材料和不能改的部分定下来
| 需要确认 | 本例内容 |
|---|---|
| 现有材料 | Windows 10/11、Windows PowerShell 5.1、当前用户已登录;C:\LearningTasks\ 下的 run.ps1、input、output。它是本地文件练习,不访问订单或供应商接口。 |
| 不能越过的边界 | 写明输入、水位、幂等、超时、有限退避、失败通知和手动停止;不无限重试。 |
| 要交付的结果 | 调度契约与失败演练记录 |
定时任务怎么设置,从“准备固定工作目录”开始做
准备固定工作目录
创建 C:\LearningTasks、input、output,保存 run.ps1。把前一天日期命名的 .txt 放进 input。
先手动演练
在该目录运行 powershell.exe -NoProfile -File .\run.ps1,分别测试正常输入、重复触发和缺失输入。执行策略由当前系统管理,不在教程中永久绕过。
注册日程
使用下方当前用户 Interactive 任务;它保存到任务计划程序,关闭当前终端不会删除计划。
检查第一次触发
主动启动一次,查看 LastTaskResult 和 run.log。正常0、失败1、暂停2是本脚本的退出约定。
接管与恢复
先禁用任务,读取 paused.flag;核对输入与部分输出,处理后移走暂停标记,再启用。不要仅删输出强行重试。
有限重试、去重与暂停的完整任务
保存在 C:\LearningTasks
$ErrorActionPreference = 'Stop'
$base = $PSScriptRoot
$paused = Join-Path $base 'paused.flag'
if (Test-Path -LiteralPath $paused) { exit 2 }
$batch = (Get-Date).AddDays(-1).ToString('yyyy-MM-dd')
$inputFile = Join-Path $base ("input\" + $batch + ".txt")
$outputFile = Join-Path $base ("output\" + $batch + ".txt")
$stateFile = Join-Path $base ("output\" + $batch + ".sha256")
try {
for ($attempt = 1; $attempt -le 3; $attempt++) {
if (Test-Path -LiteralPath $inputFile) { break }
if ($attempt -lt 3) { Start-Sleep -Seconds 10 }
}
if (!(Test-Path -LiteralPath $inputFile)) { throw "输入缺失:$batch;已检查3次" }
$hash = (Get-FileHash -LiteralPath $inputFile -Algorithm SHA256).Hash
if (Test-Path -LiteralPath $outputFile) {
if (!(Test-Path -LiteralPath $stateFile)) { throw '输出存在但无状态,人工核对' }
if ((Get-Content -LiteralPath $stateFile -Raw).Trim() -ne $hash) { throw '同批次输入已变化,人工核对' }
Add-Content -LiteralPath (Join-Path $base 'run.log') -Value "$batch skipped same-input"
exit 0
}
Copy-Item -LiteralPath $inputFile -Destination $outputFile -ErrorAction Stop
Set-Content -LiteralPath $stateFile -Value $hash
Add-Content -LiteralPath (Join-Path $base 'run.log') -Value "$batch completed"
} catch {
$message = "$batch FAILED: $($_.Exception.Message)"
Add-Content -LiteralPath (Join-Path $base 'run.log') -Value $message
Set-Content -LiteralPath $paused -Value $message
Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.MessageBox]::Show($message, '教学定时任务需处理') | Out-Null
exit 1
}注册持久日程并查看实际结果
在已准备好的目录外也可执行
$taskUser = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name $action = New-ScheduledTaskAction -Execute 'powershell.exe' -Argument '-NoProfile -File "C:\LearningTasks\run.ps1"' -WorkingDirectory 'C:\LearningTasks' $trigger = New-ScheduledTaskTrigger -Daily -At '09:00' $principal = New-ScheduledTaskPrincipal -UserId $taskUser -LogonType Interactive $settings = New-ScheduledTaskSettingsSet -MultipleInstances IgnoreNew -StartWhenAvailable Register-ScheduledTask -TaskName 'Xiaohe-Lesson-Report' -Action $action -Trigger $trigger -Principal $principal -Settings $settings Start-ScheduledTask -TaskName 'Xiaohe-Lesson-Report' Get-ScheduledTaskInfo -TaskName 'Xiaohe-Lesson-Report'
09:00 使用该 Windows 系统本地时区。IgnoreNew 只约束由这一个计划任务触发的重叠实例;不要同时手工运行脚本。Register-ScheduledTask 不加 -Force,已有同名任务时先核对而非覆盖。
人工接管与结束练习
暂停与恢复触发器
Disable-ScheduledTask -TaskName 'Xiaohe-Lesson-Report' Get-Content -LiteralPath 'C:\LearningTasks\paused.flag' # 核对输入、输出和日志后,把 paused.flag 移至留档位置;再运行下一条 Enable-ScheduledTask -TaskName 'Xiaohe-Lesson-Report' # 结束练习时在任务计划程序删除该同名任务,保留日志与输入
持久注册的参数与权限以 [Microsoft Register-ScheduledTask](https://learn.microsoft.com/en-us/powershell/module/scheduledtasks/register-scheduledtask) 为准。文件复制与状态写入之间不是事务,若只写出文件就中断,本例会停下让人工核对。
完成后的调度契约与失败演练记录
预期任务注册后每日09:00触发,缺输入最多检查3次、间隔10秒;失败写 paused.flag 并提示。相同日期与相同输入再次触发只记录 skipped;输入变化或状态不完整停止。
为什么“看不到弹窗”还不能交付
看不到弹窗
- 原因
- 用户未登录或任务没有使用 Interactive 主体
- 怎么改
- 查任务历史与run.log;无人值守改用组织已有通知通道并实际验证送达,不宣称本例可离线通知
