APLawrence.com -  Resources for Unix and Linux Systems, Bloggers and the self-employed
RSS Feeds RSS Feeds











(OLDER) <- More Stuff -> (NEWER) (NEWEST)
Printer Friendly Version
->
-> Cron, Batch and At


Cron, Batch and At





These three commands are used to run commands at some other time. They differ in their usage, their environment, and their default actions, so are sometimes a source of confusion. If you are having trouble with cron, you might want to read Cron is not working first.

If you don't know how to create the script that cron or at will call, see New To Unix

The "batch" command really just calls "at" with special flags set:

at -q b -m now
 

but "cron" is truly a totally separate command.

One of the common problems posted to the Unix newsgroups goes something like:


I have a command script.  If I run it from the command line or with "at",
it works, but if I run it with "cron" it fails.  Why?
 

Not only is this a common question, but amazingly enough, it usually generates three or four wrong answers every time it appears. The correct answer is that it fails because "cron" runs with a different environment than what you have. You have a certain PATH, you have other environment variables set, and "at" deliberately notices all that and makes sure that when your command runs, all those things will be in place. The "cron" utility does not: it has its own environment, probably very different from yours.

Note: this article covers both SCO and Linux cron. I keep the SCO stuff here for those unfortunate folks who haven't been able to move to Linux yet. There's lots here to help you do that: SCO/Linux Transition Guide is a start.

Very often, it's just the PATH that is different. For example, root's environment usually has

PATH=/bin:/etc:/usr/bin:/tcb/bin,
 

but cron (in SCO OSR5, see below for Linux which has a much smarter cron system) sets its environment to

PATH=:/bin:/usr/bin:/usr/lbin
 

Note: the man page for SCO crontab says that the PATH will be "/bin:/usr/bin:" but the above PATH is what actually happens on my 5.0.5 system. The difference is especially significant because of the placement of the lone ":", which adds "." to cron's PATH. According to the manual, the "." would end up at end of the path, and thus would be the last place searched. It actually ends up at the beginning. As the first command found is the command executed, this can cause unexpected results. Cron does cd to the home directory of the user whose cron job is being run, so "." will always refer to that directory- unless the command script itself changes directories and then issues another command.

The other likely cause for failure is a missing environment variable. Cron only has:

HOME=/ (or the home directory of the user whose job is running)
HZ=100
IFS= <TAB><LF>      (not actually set to this; edited for viewing)
LOGNAME=root  (or whomever's job is running)
MAILCHECK=600
OPTIND=1
PATH=:/bin:/usr/bin:/usr/lbin
SHELL=/bin/sh
TZ=EST5EDT
 

Linux cron has the very nice feature of being able to set environment variables directly in the crontab file ( see man 5 crontab on a Linux system). But don't make the mistake of exporting them. This doesn't work in crontab:

FOO=xyz;export FOO
 

That would end up with your scripts seeing FOO as "xyz;exort FOO" rather than the "xyz" you wanted. You don't need to worry about export anyway; cron will do that automatically.

It also allows you to control who mail is sent to when the commands generate output, or to have no mail sent at all (MAILTO=""). That saves you from having to redirect output if you don't care about anything the script has to say. Linux crontab files are found in non-standard (non-standard for Unix) places, so you should read the man pages ( or "info cron" ) carefully- it's a bit different than Unix. Also, some of the files have an extra argument: files put in /etc/cron.d specify a user before the command to be run. Don't forget that, or they won't work. And of course files in /etc/cron.daily (hourly, etc.) are just scripts that are called by "run-part"entries in /etc/crontab. Note that /etc/crontab also requires that extra "user" field. If you run "crontab -l", you'll be listing files from /var/spool/cron, and these are familiar Unix format.



If your command script requires anything variables not in cron's normal environment and not otherwise set (in the script or in a Linux crontab file), it will fail. If your script required Korn shell features, it would also fail (if cron notices that you are not running /bin/sh when you change a crontab, it will remind you that it plans to use /bin/sh. On Linux, it uses Bash).

A simple way to fix the environment issue is to use "at" to set up your environment. You can, for example, type:

at now + 1 hour <ENTER>
fakecommand <ENTER>
<CTRL-D>
 

"at" will spit back a job number. Change directories to /usr/spool/cron/atjobs and you'll see that same number listed. Notice that it is owned by root with group of cron, and that the permissions are: ---Sr-S---. Copy that file somewhere else, then rm the file in the spool area, and take a look at the copy you made. It will look something like this:

: at job
export _; _='/usr/bin/at'
export HZ; HZ='100'
export PATH; PATH=':/bin:/etc:/usr/bin:/tcb/bin:/usr/local/bin:/usr/local/etc'
export HUSHLOGIN; HUSHLOGIN='FALSE'
export LOGNAME; LOGNAME='root'
export MAIL; MAIL='/usr/spool/mail/root'
export SHELL; SHELL='/bin/sh'
export HOME; HOME='/'
export TERM; TERM='scoansi'
export PWD; PWD='/tmp'
export TZ; TZ='EST5EDT'
export ENV; ENV='/.kshrc'
:
#       @(#) proto 23.2 91/08/29 
#
#       Copyright (C) 1988-1991 The Santa Cruz Operation, Inc.
#               All Rights Reserved.
#       The information in this file is provided for the exclusive use of
#       the licensees of The Santa Cruz Operation, Inc.  Such users have the
#       right to use, modify, and incorporate this code into other products
#       for purposes authorized by the license agreement provided they include
#       this notice and the associated copyright notice with any such product.
#       The information in this file is provided "AS IS" without warranty.
#

#ident  "@(#)adm:.proto 1.2"
cd /tmp
ulimit 4194303
umask 22
fakecommand
 

Notice what great pains "at" has gone to to match your environment. Not only do you have all your environment variables, but your ulimit and umask have been matched and it has even cd'd you to the directory you were in when you issued the command. So now use that script from crontab rather than "fakecommand" directly. That is, if you copied the at script to /usr/local/bin/runfake, it is /usr/local/bin/runfake that you would invoke from cron, not "fakecommand".

Recently someone asked me why their crontab wasn't working. They understood that they needed to set their environment, but what they did was something like this:

17      5       *       *       *       ./setmyenv.cmd;domystuff.cmd
 

That'll never work, and wouldn't work from the shell either. You would need to add a ". ./setmyenv.cmd" inside "domystuff" (that's dot space dot slash setnyenv.cmd).

You probably know that you do not edit the crontab files directly (on Linux that's fine, but not on most Unixes). Some people use "crontab -e", but a more safe procedure is:

crontab -l > /tmp/mycrontab
vi /tmp/mycrontab
(make your changes)
crontab /tmp/mycrontab
 

Or, if for another user:

crontab -u john -l > /tmp/mycrontab
vi /tmp/mycrontab
(make your changes)
crontab -u john /tmp/mycrontab
 

Two reasons that is safer: first, if your EDITOR variable is accidentally set to something you don't know (as it may very well be on an unfamiliar system), you may accidentally wipe out the crontab getting out of it. Another reason for avoiding -e is the proximity of e and r on your keyboard - if you type -r, that crontab is gone instantly.

By the way, some old systems wouldn't work if you did (for example) "export EDITOR=vi" rather than "export EDITOR=/usr/bin/vi". This was simply a matter of whether they used execlp instead of execl (execlp searches $PATH).

Be careful with crontabs set to other users. Remember that cron cd's to the user's directory when it starts up your job. If the user's directory doesn't exist cron fails and sends mail to that user. That doesn't sound too horrible, does it? Well, on the older 3.2v4.2 release, there was some bug somewhere that sometimes caused /usr/sys to be removed. The "sys" user still existed, and still had its crontab file, but when cron tried to run, it couldn't cd to the non-existent home directory. This caused it to start sending mail to "sys" complaining. That wouldn't have been too bad, but who reads "the "sys" user's mail? Usually nobody, so the mail file would build up larger and larger. Eventually it would start to affect the performance of mmdf, and mmdf would get backed up- it couldn't clear out its own spool directories quite as fast as they were growing, which meant that the size of the directories in /usr/spool/mmdf started growing. The larger a directory is, the more time it takes to search it, so this made mmdf run even more slowly, which caused it to get more behind, which, of course, caused the directories to grow larger yet... and to add insult to injury, mmdf would itself start generating messages about mail it couldn't deliver (now that's dumb!), and those only added to the problem. Eventually this would get bad enough to affect performance, because mmdf was spending every spare cpu cycle available trying to deliver mail. So sar would show 0 idle time, the disk would be thrashing as mmdf tried to catch up, and performanced nose dived. What a mess, and all because of a missing directory.

The "at" and "batch" programs are much less complex. Batch takes no arguments; it just runs your program. The details of these are covered in the man pages.

Note for some SCO 5.0.6 users

Some versions of 5.0.6 cron had a bug where a cron job could be run twice. The fix is to get the proper version of cron or (if that's not possible) be sure your script can handle that possibility (set some flag that says it has run or is running and exit if the other instance sees that).



If this page was useful to you, please help others find it:  





20 comments




More Articles by - Find me on Google+



Click here to add your comments
- no registration needed!





Thu Jun 9 15:40:50 2005: 635   anonymous


you say that
crontab -l > /tmp/mycrontab 
vi /tmp/mycrontab
(make your changes)
crontab /tmp/mycrontab
is safer than
 
crontab -e
but the only thing your more complicated procedure does is keep the 'mycrontab' file around as a backup. You could make the cya backup and then run crontab, and achieve the same result more easily and with less chance of error.






Thu Jun 9 17:09:41 2005: 637   TonyLawrence

gravatar
Wrong.

With crontab -e, if your environment is whacked because your terminal emulator isn't right, or you get thrown into an editor you don't undertstand because the jackass before you set EDITOR and you didn't notice, you can very easily completely lose what was already there.

I hear this nonsense all the time. It's bad, bad advice.



Fri May 28 00:09:33 2010: 8641   DC

gravatar


I have bumped into this issue a few times. the uninitiated often don't set the path when setting the crontab. for me its often 'php' instead of '/usr/bin/php' or even '`which php`' but it seems totally odd to me that cron doesn't pick up the correct path. shouldnt cron when switching users and just before running the command pick up that users env. so root crons get the root env. or user suchandsuch gets user suchandsuch's env.

Only seems logical to me.

Anyway nice explanation.
DC



Tue Jan 18 15:54:35 2011: 9239   anonymous

gravatar


Here is an example of how you can do (without RTFM)

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
# m h dom mon dow command
*/1 * * * * php /path/to/foo.php



Tue Jan 18 16:07:14 2011: 9240   TonyLawrence

gravatar


Here is an example of how you can do

No, it isn't. That is a Linux vixie cron specific example.

The world of Unix is dominated by Linux, but that is not all there is.



Mon Jun 11 14:28:43 2012: 11081   gokul

gravatar


Hi Guys,
I am new to UNIX,I have a script that runs every Mon-Sat,It takes the dat file and load the content to the data base.it is loaded two different file at the same time in database. when i run this script manually it works fine.but if i add this to crontab it is running but it skip the loading part and doesn't throws any error.Please help me to solve this



Mon Jun 11 14:33:09 2012: 11082   TonyLawrence

gravatar


Did you bother to READ anything above or did you (as I suspect) just read the title and immediately jump to ask a question?



Mon Jun 11 14:34:32 2012: 11083   TonyLawrence

gravatar


Try http://aplawrence.com/Unixart/crontab_not_running.html also..

and READ it this time. I'm happy to answer questions that indicate at least some effort to understand what was written.



Sat Dec 6 17:28:01 2014: Website: 12566   prat

gravatar


how to write cron jobs other than crontab -e command for root and normal users ? basically crontab -e changes which file at background ?



Sat Dec 6 18:58:08 2014: Website: 12568   TonyLawrence

gravatar


That depends on the OS. Sys V crontabs are in /usr/spool/cron/crontab , but Linux has them in several places: /var/spool/cron for user's files, and both /etc/crontab and files in /etc/cron.d (those in /etc/cron.d include an extra column which says which user to run as). Unix systems won't notice changes made to these files so you should use crontab. You don't need to use -e - I use crontab -l > /tmp/somefile; vi /tmp/somefile; crontab /tmp/somefile



Sun Dec 7 02:44:58 2014: Website: 12570   prat

gravatar


Thanks for the update.
what do you mean by ` OS. Sys V crontabs` ? i am using redhat linux and the crontab in rhel5 is vixie-cron and in rhel6 it is cronie. so i just asked is there any other way to write jobs other than common command crontab -e for root and normal users. one way you have shown.is there any other way ? like creating a file direct inside /var/spool/cron/username and write the cron job inside it. will it help to schedule the cron job ? what are the other ways as well



Sun Dec 7 02:59:36 2014: Website: 12571   chu

gravatar


how to write cron jobs which will run after every 1hr:30mins



Sun Dec 7 04:50:46 2014: Website: 12572   crontabexpert

gravatar


Hi Sir,
what is run-parts scripts in /etc/crontab in redhat5. what run-parts scripts do here.



Sun Dec 7 11:23:06 2014: Website: 12573   TonyLawrence

gravatar


I don't have any RedHat 5 to look at. Examine them yourself and if you have questions, ask.



Sun Dec 7 11:40:22 2014: Website: 12574   TonyLawrence

gravatar


Yes, you can write directly if you want on Linux but not on Sys V Unix.








Sun Dec 7 11:43:12 2014: Website: 12575   TonyLawrence

gravatar


To run every 90 minutes, I'd use an "at" job that reschedules itself, but see http://aplawrence.com/Basics/run_command_periodically.html also.



Sun Dec 7 14:49:45 2014: Website: 12576   chu

gravatar


i can't find any example that show e.g. for 1hr:30min. can you show it
here



Sun Dec 7 15:10:23 2014: Website: 12577   TonyLawrence

gravatar


No. I think you are doing course homework and are too lazy to read what I gave you. Any intelligent person could figure it out from that. Stop trying to cheat and use your brain.



Tue Dec 9 04:07:55 2014: Website: 12579   crontabexpert

gravatar


hi sir,
here is that below run-parts script. can you check let us know what it does actually.
since i am new in linux and not aware of scripting. need your help.

(script deleted)



Tue Dec 9 09:08:49 2014: Website: 12581   TonyLawrence

gravatar


here is that below run-parts script. can you check let us know what it does actually.

Yes. My charge for that service is $250.00. See http://aplawrence.com/rightnow.html

Don't miss responses! Subscribe to Comments by RSS or by Email

Click here to add your comments


If you want a picture to show with your comment, go get a Gravatar

Kerio Samepage


Have you tried Searching this site?

Unix/Linux/Mac OS X support by phone, email or on-site: Support Rates

This is a Unix/Linux resource website. It contains technical articles about Unix, Linux and general computing related subjects, opinion, news, help files, how-to's, tutorials and more. We appreciate comments and article submissions.

Publishing your articles here

Jump to Comments



Many of the products and books I review are things I purchased for my own use. Some were given to me specifically for the purpose of reviewing them. I resell or can earn commissions from the sale of some of these items. Links within these pages may be affiliate links that pay me for referring you to them. That's mostly insignificant amounts of money; whenever it is not I have made my relationship plain. I also may own stock in companies mentioned here. If you have any question, please do feel free to contact me.

I am a Kerio reseller. Articles here related to Kerio products reflect my honest opinion, but I do have an obvious interest in selling those products also.

Specific links that take you to pages that allow you to purchase the item I reviewed are very likely to pay me a commission. Many of the books I review were given to me by the publishers specifically for the purpose of writing a review. These gifts and referral fees do not affect my opinions; I often give bad reviews anyway.

We use Google third-party advertising companies to serve ads when you visit our website. These companies may use information (not including your name, address, email address, or telephone number) about your visits to this and other websites in order to provide advertisements about goods and services of interest to you. If you would like more information about this practice and to know your choices about not having this information used by these companies, click here.

pavatar.jpg

This post tagged:

       - Basics
       - Kernel
       - Linux
       - SCO_OSR5
       - Shell



















My Troubleshooting E-Book will show you how to solve tough problems on Linux and Unix systems!


book graphic unix and linux troubleshooting guide



Buy Kerio from a dealer
who knows tech:
I sell and support

Kerio Connect Mail server, Control, Workspace and Operator licenses and subscription renewals



Click and enter your name and phone number to call me about Kerio® products right now (Flash required)