用 systemd-run 创建临时定时任务

systemd-run 可以把任意命令包装成临时的 timer/service 单元——无需编写单元文件即可实现类似 cron 的调度。

Linux计划任务systemd定时器中风险
运行 `sudo systemd-run --on-active=30min <命令>` 可在 30 分钟后执行命令,或用 `--on-calendar='Mon *-*-* 09:00:00'` 按日历模式重复执行。

01命令

命令
$ sudo systemd-run --on-active=30min apt-get update

02作用说明

systemd-run 创建的临时单元只存在于内存中:配合 --on-active(延迟)或 --on-calendar(cron 风格的时间模式),它会自动生成一对 timer 和 service 单元。这些单元默认使用 run-rabcdef.timer 这类自动生成的名字,可以用 `--unit=myjob` 指定名字,然后用 `systemctl list-timers` 查找。它们在执行完或重启后就会消失,因此非常适合一次性的延迟操作而非长期计划任务。

03风险

风险中风险
使用条件systemd-based distribution; transient units disappear after running or reboot (use --unit=NAME to give them a predictable name).
!注意: 临时单元在重启后会丢失——需要长期重复的任务请改用正式的 timer 单元。

04撤销

撤销
$ systemctl stop run-<id>.timer run-<id>.service

05来源

  • systemd-run(1) - run programs in transient units
    man7.org Linux man-pages · technical · 2026-09-17
    依据: --on-active= creates a transient timer unit which elapses after a relative timespan; --on-calendar= uses calendar event expressions; the command then runs in a transient service unit.

最后验证: 2026-09-17 · 分类: 系统与设置

06相关方案