Scheduling jobs in UNIX without cron
If you happen to be unfortunate enough to be in a system where you're not allowed to use cron
, you might be able to do something similar with at
instead. Here's a script that reschedules itself to run the next day at 8:45am:
#!/bin/bash
the_main_thing &>/dev/null
[[ $0 = /* ]] && script=$0 || script=$PWD/$0
at -f "$script" 0845 &>/dev/null
the_main_thing
is the command or script you want to run periodically.
The purpose of [[ $0 = /* ]] && script=$0 || script=$PWD/$0
is to get the absolute path of the current script itself.
In at -f "$script" 0845 &>/dev/null
, the -f
is to specify the script to run: the current script itself with absolute path, otherwise it might not work.
To run something every 5 hours, you can use relative times, for example:
at -f "$script" 'now + 5 hours' &>/dev/null
Similar to cron
, the output of scheduled at
jobs is emailed to the UNIX account. To prevent polluting the mailbox, it's probably a good idea to redirect both with &> /dev/null
, and you might want to do the same for the_main_thing
too.
To view your scheduled tasks, use atq
. To remove scheduled tasks, use atrm
.
Written by Janos Gyerik
Related protips
2 Responses
Thanks! It's harder than it should be to find fully explained UNIX tips. Keep it up!
Thanks for sharing. I adapted your technique to separate the scheduling from the task. For example, save the following as scheduled
#!/bin/bash
# run script at scheduled time
# (derived from script by Janos Gyerik
# https://coderwall.com/p/eilosa/scheduling-jobs-in-unix-without-cron)
#
# usage: scheduled <when> <script> [args...]
# e.g. scheduled '7:15' script arg1 arg2
# scheduled 'now + 5 minutes' script arg1 arg2
# also note script will execute in $PWD
[[ $0 = /* ]] && script=$0 || script=$PWD/$0
when="$1"
shift
echo "$script '$when' $*" | at "$when" &>/dev/null
$* &>/dev/null
Then use with: scheduled 'now + 10 minutes' another_script arg1 arg2 arg3