Test a weekly cron job

LinuxCronDebian

Linux Problem Overview


I have a #!/bin/bash file in cron.week directory.

Is there a way to test if it works? Can't wait 1 week

I am on Debian 6 with root

Linux Solutions


Solution 1 - Linux

Just do what cron does, run the following as root:

run-parts -v /etc/cron.weekly

... or the next one if you receive the "Not a directory: -v" error:

run-parts /etc/cron.weekly -v

Option -v prints the script names before they are run.

Solution 2 - Linux

A wee bit beyond the scope of your question... but here's what I do.

The "how do I test a cron job?" question is closely connected to "how do I test scripts that run in non-interactive contexts launched by other programs?" In cron, the trigger is some time condition, but lots of other *nix facilities launch scripts or script fragments in non-interactive ways, and often the conditions in which those scripts run contain something unexpected and cause breakage until the bugs are sorted out. (See also: https://stackoverflow.com/a/17805088/237059 )

A general approach to this problem is helpful to have.

One of my favorite techniques is to use a script I wrote called 'crontest'. It launches the target command inside a GNU screen session from within cron, so that you can attach with a separate terminal to see what's going on, interact with the script, even use a debugger.

To set this up, you would use "all stars" in your crontab entry, and specify crontest as the first command on the command line, e.g.:

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

So now cron will run your command every minute, but crontest will ensure that only one instance runs at a time. If the command takes time to run, you can do a "screen -x" to attach and watch it run. If the command is a script, you can put a "read" command at the top to make it stop and wait for the screen attachment to complete (hit enter after attaching)

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.

#!/bin/bash

# crontest
# See https://github.com/Stabledog/crontest for canonical source.

# 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

Solution 3 - Linux

After messing about with some stuff in cron which wasn't instantly compatible I found that the following approach was nice for debugging:

crontab -e

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

This will run the task once a minute and you can simply look in the /tmp/cron_debug_log.log file to figure out what is going on.

It is not exactly the "fire job" you might be looking for, but this helped me a lot when debugging a script that didn't work in cron at first.

Solution 4 - Linux

I'd use a lock file and then set the cron job to run every minute. (use crontab -e and * * * * * /path/to/job) That way you can just keep editing the files and each minute they'll be tested out. Additionally, you can stop the cronjob by just touching the lock file.

    #!/bin/sh
    if [ -e /tmp/cronlock ]
    then
    	echo "cronjob locked"
    	exit 1
    fi
    
    touch /tmp/cronlock
    <...do your regular cron here ....>
    rm -f /tmp/cronlock

Solution 5 - Linux

What about putting it into cron.hourly, waiting until the next run of hourly cron jobs, then removing it? That would run it once within an hour, and in the cron environment. You can also run ./your_script, but that won't have the same environment as under cron.

Solution 6 - Linux

Aside from that you can also use:

http://pypi.python.org/pypi/cronwrap

to wrap up your cron to send you an email upon success or failure.

Solution 7 - Linux

None of these answers fit my specific situation, which was that I wanted to run one specific cron job, just once, and run it immediately.

I'm on a Ubuntu server, and I use cPanel to setup my cron jobs.

I simply wrote down my current settings, and then edited them to be one minute from now. When I fixed another bug, I just edited it again to one minute from now. And when I was all done, I just reset the settings back to how they were before.

Example: It's 4:34pm right now, so I put 35 16 * * *, for it to run at 16:35.

It worked like a charm, and the most I ever had to wait was a little less than one minute.

I thought this was a better option than some of the other answers because I didn't want to run all of my weekly crons, and I didn't want the job to run every minute. It takes me a few minutes to fix whatever the issues were before I'm ready to test it again. Hopefully this helps someone.

Solution 8 - Linux

The solution I am using is as follows:

  1. Edit crontab(use command :crontab -e) to run the job as frequently as needed (every 1 minute or 5 minutes)
  2. Modify the shell script which should be executed using cron to prints the output into some file (e.g: echo "Working fine" >>
    output.txt)
  3. Check the output.txt file using the command : tail -f output.txt, which will print the latest additions into this file, and thus you can track the execution of the script

Solution 9 - Linux

I normally test by running the job i created like this:

It is easier to use two terminals to do this.

run job:

#./jobname.sh

go to:

#/var/log and run 

run the following:

#tailf /var/log/cron

This allows me to see the cron logs update in real time. You can also review the log after you run it, I prefer watching in real time.

Here is an example of a simple cron job. Running a yum update...

#!/bin/bash
YUM=/usr/bin/yum
$YUM -y -R 120 -d 0 -e 0 update yum
$YUM -y -R 10 -e 0 -d 0 update

Here is the breakdown:

First command will update yum itself and next will apply system updates.

-R 120 : Sets the maximum amount of time yum will wait before performing a command

-e 0 : Sets the error level to 0 (range 0 - 10). 0 means print only critical errors about which you must be told.

-d 0 : Sets the debugging level to 0 - turns up or down the amount of things that are printed. (range: 0 - 10).

-y : Assume yes; assume that the answer to any question which would be asked is yes

After I built the cron job I ran the below command to make my job executable.

#chmod +x /etc/cron.daily/jobname.sh 

Hope this helps, Dorlack

Solution 10 - Linux

sudo run-parts --test /var/spool/cron/crontabs/

files in that crontabs/ directory needs to be executable by owner - octal 700

source: man cron and NNRooth's

Solution 11 - Linux

I'm using Webmin because its a productivity gem for someone who finds command line administration a bit daunting and impenetrable.

There is a "Save and Run Now" button in the "System > Scheduled Cron Jobs > Edit Cron Job" web interface.

It displays the output of the command and is exactly what I needed.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiondynamicView Question on Stackoverflow
Solution 1 - LinuxNNRoothView Answer on Stackoverflow
Solution 2 - LinuxStabledogView Answer on Stackoverflow
Solution 3 - LinuxAutomaticoView Answer on Stackoverflow
Solution 4 - Linuxdave fernholzView Answer on Stackoverflow
Solution 5 - LinuxJeremiah WillcockView Answer on Stackoverflow
Solution 6 - LinuxMuhammad Lukman LowView Answer on Stackoverflow
Solution 7 - LinuxBen CView Answer on Stackoverflow
Solution 8 - LinuxAbhilashView Answer on Stackoverflow
Solution 9 - LinuxDorlackView Answer on Stackoverflow
Solution 10 - Linuxn611x007View Answer on Stackoverflow
Solution 11 - LinuxKickahaView Answer on Stackoverflow