linux cron - ghdrako/doc_snipets GitHub Wiki

Alternative

  • anacron,
  • fcron,
  • jobber
  • systemd timer

Execute in last day of month

46 09 28-31 * * [ $(date -d +1day +\%d) -eq 1 ] && /slog/app/bin/imp_tgen499.sh > /tmp/imp_tgen499.cron 2>&1

Commands

/etc/cron.allow # allow cron jobs to be added for users
echo akepka >> /etc/cron.allow # as root

/etc/cron.d/cron.deny # denied access to cron job access by entering their usernames in the file

# Check cron service on Linux system
sudo systemctl status cron.service

crontab -e              # edits crontab entries to add, delete, or edit cron jobs
crontab -l              # list all the cron jobs for the current user.
crontab -u username -l # list another user's crons.
crontab -u username -e # edit another user's crons.

Syntax

*   *   *   *   *  sh /path/to/script/script.sh
|   |   |   |   |              |
|   |   |   |   |      Command or Script to Execute        
|   |   |   |   |
|   |   |   |   |
|   |   |   |   |
|   |   |   | Day of the Week(0-6)
|   |   |   |
|   |   | Month of the Year(1-12)
|   |   |
|   | Day of the Month(1-31)  
|   |
| Hour(0-23)  
|
Min(0-59)
00 15 * * Thu /usr/local/bin/mycronjob.sh  # execute every Thursday at 3 p.m.
*/10 * * * * /scripts/monitor.sh           # execute on every 10 minutes
*/5 08-18/2 * * * /usr/local/bin/mycronjob.sh # execute on every 5 minutes during every hour between 8 a.m. and 5:58 p.m.
01 09-17 * * * /usr/local/bin/hourlyreminder.sh # execute at regular times(every houer) during normal business hours
* * * jan,may,aug *  /script/script.sh      # execute on selected months
0 17 * * sun,fri  /script/script.sh  # execute on selected days
0 2 * * sun  [ $(date +%d) -le 07 ] && /script/script.sh # execute on first sunday of every month
0 */4 * * * /scripts/script.sh  # execute on every four hours

Schedule a cron to execute on every 30 Seconds.

To schedule a task to execute every 30 seconds is not possible by time parameters, But it can be done by schedule same cron twice as below.

* * * * * /scripts/script.sh
* * * * *  sleep 30; /scripts/script.sh

Multiple tasks

To configure multiple tasks with single cron, Can be done by separating tasks by the semicolon ( ; ) or (&&).

* * * * * /scripts/script.sh; /scripts/scrit2.sh
0 12 * * * /ścieżka/do/skrypt1.sh && /ścieżka/do/skrypt2.sh # Skrypt skrypt2.sh uruchomi się tylko wtedy, gdy skrypt1.sh zakończy się sukcesem (kod wyjścia 0).

Schedule tasks to execute on yearly ( @yearly timestamp is similar to “0 0 1 1 *”. It will execute a task on the first minute of every year

@yearly /scripts/script.sh

Schedule tasks to execute on monthly @monthly timestamp is similar to “0 0 1 * *”. It will execute a task in the first minute of the month.

@monthly /scripts/script.sh

Schedule tasks to execute on Weekly ( @weekly ).

@weekly timestamp is similar to “0 0 1 * mon”. It will execute a task in the first minute of the week

@weekly /bin/script.sh

Schedule tasks to execute on daily @daily timestamp is similar to “0 0 * * *”. It will execute a task in the first minute of every day

@daily /scripts/script.sh

Schedule tasks to execute on hourly @hourly timestamp is similar to “0 * * * *”. It will execute a task in the first minute of every hour

@hourly /scripts/script.sh

Schedule tasks to execute on system reboot ( @reboot ).

@reboot is useful for those tasks which you want to run on your system startup. It will be the same as system startup scripts. It is useful for starting tasks in the background automatically.

@reboot /scripts/script.sh

Redirect Cron Results to specified email account.

By default, cron sends details to the current user where cron is scheduled. If you want to redirect it to your other account, can be done by setup MAIL variable like below

# crontab -l
MAIL=blaataap
0 2 * * * /script/backup.sh

Taking backup of all crons to plain text file. Check current scheduled cron:

# crontab -l
MAIL=blaataap
0 2 * * * /script/backup.sh

Backup cron to text file:

# crontab -l > cron-backup.txt
# cat cron-backup.txt
MAIL=blaataap
0 2 * * * /script/backup.sh

Removing current scheduled cron:

# crontab -r
# crontab -l

no crontab for root

Restore crons from text file:

# crontab cron-backup.txt
# crontab -l
MAIL=blaataap
0 2 * * * /script/backup.sh

Troubleshoot

# check cron logs
var/log/cron
/var/log/syslog
# Redirect cron output to a file
* * * * * sh /path/to/script.sh &> log_file.log

Testing cron

run the task once a minute

* * * * * <command> #Runs every minute

in bash:

* * * * * /path/to/prog var1 var2 &>>/tmp/cron_debug_log.log

in other shell:

* * * * * /path/to/prog var1 var2 >>/tmp/cron_debug_log.log 2>&1

run-parts uruchamia wszystkie pliki wykonywalne w katalogu inne ignoruje just runs the scripts of a given directory. Nothing to do with cron

run-parts -v /etc/cron.weekly
run-parts /etc/cron.weekly -v
* * * * *  /usr/bin/env > /home/username/cron-env2

run-as-cron:

#!/bin/sh

. "$1"
exec /usr/bin/env -i "$SHELL" -c ". $1; $2"

use:

run-as-cron <cron-environment> <command>

e.g.

run-as-cron /home/username/cron-env 'echo $PATH'

you can do a "screen -x" to attach and watch it run

* * * * * crontest /command/to/be/tested --param1 --param2

If your command is a bash script, you can do this instead:

* * * * * crontest --bashdb /command/to/be/tested --param1 --param2

Now, if you attach with "screen -x", you'll be facing an interactive bashdb session, and you can step through the code, examine variables, etc.

crontest:

#!/bin/bash

# crontest
#
# Test wrapper for cron tasks.  The suggested use is:
#
#  1. When adding your cron job, use all 5 stars to make it run every minute
#  2. Wrap the command in crontest
#        
#
#  Example:
#
#  $ crontab -e
#     * * * * * /usr/local/bin/crontest $HOME/bin/my-new-script --myparams
#
#  Now, cron will run your job every minute, but crontest will only allow one
#  instance to run at a time.  
#
#  crontest always wraps the command in "screen -d -m" if possible, so you can
#  use "screen -x" to attach and interact with the job.   
#
#  If --bashdb is used, the command line will be passed to bashdb.  Thus you
#  can attach with "screen -x" and debug the remaining command in context.
#
#  NOTES:
#   - crontest can be used in other contexts, it doesn't have to be a cron job.
#       Any place where commands are invoked without an interactive terminal and
#       may need to be debugged.
#
#   - crontest writes its own stuff to /tmp/crontest.log
#
#   - If GNU screen isn't available, neither is --bashdb
#

crontestLog=/tmp/crontest.log
lockfile=$(if [[ -d /var/lock ]]; then echo /var/lock/crontest.lock; else echo /tmp/crontest.lock; fi )
useBashdb=false
useScreen=$( if which screen &>/dev/null; then echo true; else echo false; fi )
innerArgs="$@"
screenBin=$(which screen 2>/dev/null)

function errExit {
    echo "[-err-] $@" | tee -a $crontestLog >&2
}

function log {
    echo "[-stat-] $@" >> $crontestLog
}

function parseArgs {
    while [[ ! -z $1 ]]; do
        case $1 in
            --bashdb)
                if ! $useScreen; then
                    errExit "--bashdb invalid in crontest because GNU screen not installed"
                fi
                if ! which bashdb &>/dev/null; then
                    errExit "--bashdb invalid in crontest: no bashdb on the PATH"
                fi

                useBashdb=true
                ;;
            --)
                shift
                innerArgs="$@"
                return 0
                ;;
            *)
                innerArgs="$@"
                return 0
                ;;
        esac
        shift
    done
}

if [[ -z  $sourceMe ]]; then
    # Lock the lockfile (no, we do not wish to follow the standard
    # advice of wrapping this in a subshell!)
    exec 9>$lockfile
    flock -n 9 || exit 1

    # Zap any old log data:
    [[ -f $crontestLog ]] && rm -f $crontestLog

    parseArgs "$@"

    log "crontest starting at $(date)"
    log "Raw command line: $@"
    log "Inner args: $@"
    log "screenBin: $screenBin"
    log "useBashdb: $( if $useBashdb; then echo YES; else echo no; fi )"
    log "useScreen: $( if $useScreen; then echo YES; else echo no; fi )"

    # Were building a command line.
    cmdline=""

    # If screen is available, put the task inside a pseudo-terminal
    # owned by screen.  That allows the developer to do a "screen -x" to
    # interact with the running command:
    if $useScreen; then
        cmdline="$screenBin -D -m "
    fi

    # If bashdb is installed and --bashdb is specified on the command line,
    # pass the command to bashdb.  This allows the developer to do a "screen -x" to
    # interactively debug a bash shell script:
    if $useBashdb; then
        cmdline="$cmdline $(which bashdb) "
    fi

    # Finally, append the target command and params:
    cmdline="$cmdline $innerArgs"

    log "cmdline: $cmdline"


    # And run the whole schlock:
    $cmdline 

    res=$?

    log "Command result: $res"


    echo "[-result-] $(if [[ $res -eq 0 ]]; then echo ok; else echo fail; fi)" >> $crontestLog

    # Release the lock:
    9<&-
fi
⚠️ **GitHub.com Fallback** ⚠️