|
Softpanorama |
May the source be with you, but remember the KISS principle ;-)
Softpanorama Search
|
| News | Job schedulers | Minitutorial | Recommended Links | |
| cron.allow | cron.deny | at and batch commands | Humor |
Etc |
Cron is a task scheduler for Unix servers. Linux and OpenSolaris use Vixie cron which is richer in facilities than traditional SysV cron daemon. Vixie cron is a compatible with SysV cron. To determine if Vixie cron is installed, use the rpm -q cron command on Suse 10 and rpm -qi vixie-cron on Red Hat. To determine if the service is running, use the command /sbin/service crond status.
It also supports
Cron uses several files to control its behaviors:
Implementations are different in Red Hat and Suse 10.
SHELL=/bin/sh PATH=/usr/bin:/usr/sbin:/sbin:/bin:/usr/lib/news/bin MAILTO=root # # check scripts in cron.hourly, cron.daily, cron.weekly, and cron.monthly # -*/15 * * * * root test -x /usr/lib/cron/run-crons && /usr/lib/cron/run-crons >/dev/nul l 2>&1
On Suse and Red Hat cron also can have includes (actually simple batch files) called from predefined four directories:
In both Suse and Red Hat there is a master crontab file /etc/crontab that like /etc/profile is always executed first and contains several settings and invocation of script that process four predefined directories.
Details of implementation are different for Red Hat and Suse.
In Red Hat the master crontab file /etc/crontab contains the following lines
SHELL=/bin/bash PATH=/sbin:/bin:/usr/sbin:/usr/bin MAILTO=root HOME=/ # run-parts 01 * * * * root run-parts /etc/cron.hourly 02 4 * * * root run-parts /etc/cron.daily 22 4 * * 0 root run-parts /etc/cron.weekly 42 4 1 * * root run-parts /etc/cron.monthly
Bourne script run-parts contains for loop which executes all components of corresponding directory one by one.
There is also "master" crontab at /etc/crontab that like /etc/profile is always executed. But details and script used are different:
SHELL=/bin/sh PATH=/usr/bin:/usr/sbin:/sbin:/bin:/usr/lib/news/bin MAILTO=root # # check scripts in cron.hourly, cron.daily, cron.weekly, and cron.monthly # -*/15 * * * * root test -x /usr/lib/cron/run-crons && /usr/lib/cron/run-crons >/dev/nul l 2>&1
Suse 10 also uses four directories
Each of those can contain scripts which will be executed by shell script /usr/lib/cron/run-crons. the latter is evoked each 15 minutes.
From the content of the script you can see, for example, that time of execution of scripts in /etc/cron.daily is controlled by env. variable $DAILY_TIME which is set in /etc/sysconfig/cron system file. You also see that configuration file /etc/sysconfig/cron is included at the beginning of the script.
This is an example of unnecessary complexity that desire to create more flexible environment often introduces.
A crontab file contains instructions to
the daemon of the general form: ``run this command at this time on this date''.
Each user has their own crontab, and commands in any given crontab will be
executed as the user who owns the crontab.
Blank lines and leading spaces and tabs are ignored.
Lines whose first non-space character is a pound-sign (#) are comments, and
are ignored. Note that comments are not allowed on the same line as
cron commands, since they will be taken to be part of the command. Similarly,
comments are not allowed on the same line as environment variable settings.
An active line in a crontab will be either an environment
setting or a cron command. An environment setting is of the form,
name = value
where the spaces around the equal-sign (=) are optional,
and any subsequent non-leading spaces in value will
be part of the value assigned to name.
The value string may be placed in quotes (single or
double, but matching) to preserve leading or trailing blanks. The
name string may also be placed in quote
(single or double, but matching) to preserve
leading, trailing or inner blanks.
Several environment variables are set up automatically
by the
cron(8) daemon. SHELL is set to /bin/sh,
PATH is set to /usr/bin:/bin, and LOGNAME
and HOME are set from the /etc/passwd line of the
crontab's owner. HOME, PATH and SHELL may be overridden by settings
in the crontab; LOGNAME may not.
One line of cron table specifies one cron job. A cron job is a specific task that runs a certain number of times per minute, day, week, or month on your server. For example, you can use a cron job to automate a daily MySQL database backup. The main problem with cron jobs is that if they aren't properly configured they can cause high server loads which may result in suspension of your site with your web host. If you are able, configure your cron job so that the results of running the scheduled script are emailed to you.
There are two main ways by which you create a cron job on hosting Web server. Using your administration panel ( most *nix webhosting control panels offer some sort of interface to Cron) or using shell access to your server. Panel is the easiest way; shell access requires knowledge of UNIX editing commands.Crontab has the
structure shown in the table:
|
Field
|
Meaning
|
Allowed range
|
Example
|
|
1
|
Minutes that have to pass after the selected
hour in order to execute the task
|
0-59
|
30, which
means 30 minutes after the selected hour
|
|
2
|
Hours at which the task has to be executed
|
0-23
|
04, which
means at 4 O'clock in the morning
|
|
3
|
Days of the month on which this task has
to be executed
|
1-31
|
*, which
means that every day of the selected month
|
|
4
|
Months during which the task has to be executed
|
1-12
|
3-5,
which means run the task in the months of March, April & May
First 3 letters of the Month name. Case doesn't matter. E.g.
Jan
|
|
5
|
Days of the week on which this task has
to be run
|
0-7
|
* means
all days of the selected weeks Numeric value or first 3 letters
of the Day name. Case doesn't matter (Sun or sun)
(0 or 7 is Sun, 1 is Mon...) |
|
6
|
Name of the program (task) to be executed
|
Any program
|
|
|
|||||||
A field may be an asterisk (*), which always stands for ``first-last''.
Ranges of numbers are allowed. Ranges are two numbers separated with a hyphen. The specified range is inclusive. For example, 8-11 for an ``hours'' entry specifies execution at hours 8, 9, 10 and 11.
Lists are allowed. A list is a set of numbers (or ranges) separated by commas. Examples: ``1,2,5,9'', ``0-4,8-12''.
Step values can be used in conjunction with ranges. Following a range with ``/
Names can also be used for the ``month'' and "day of week'' fields. Use the first three letters of the particular day or month (case doesn't matter). Ranges or lists of names are not allowed.
The ``sixth'' field (the rest of the line) specifies the command to be run. The entire command portion of the line, up to a newline or % character, will be executed by /bin/sh or by the shell specified in the SHELL variable of the /etc/crontab
Percent-signs (%) in the command, unless escaped with backslash (\), will be changed into newline characters, and all data after the first % will be sent to the command as standard input.
Note: The day of a command's execution can be specified by two fields
--- day of month, and day of week. If both fields are restricted (ie, aren't *),
the command will be run when either field matches the current time. For example,
``30 4 1,15 * 5'' would cause a command to be run at 4:30 am on the 1st and 15th
of each month, plus every Friday.
Instead of the first five fields, in vixie-cron one of eight predefined macros may be used:
string meaning
------ -------
@reboot Run once, at startup.
@yearly Run once a year, "0 0 1 1 *".
@annually (same as @yearly)
@monthly Run once a month, "0 0 1 * *".
@weekly Run once a week, "0 0 * * 0".
@daily Run once a day, "0 0 * * *".
@midnight (same as @daily)
@hourly Run once an hour, "0 * * * *".
If you are in one of the countries that observe Daylight Savings Time, jobs scheduled during the rollback or advance will be affected. In general, it is not a good idea to schedule jobs from 1pm to 3pm.
For US timezones (except parts of IN, AZ, and HI) the time shift occurs at 2AM local time. For others, the output of the zdump(8) program's verbose (-v) option can be used to determine the moment of time shift.
To list and edit crontab one should use crontab command which copies the specified
file or standard input if no file is specified, into a directory that holds all
users' crontabs.
The -e option edits a copy of the current users' crontab file or creates
an empty file to edit if crontab does not exist.
The-r option removes a user's crontab from the crontab directory.
The -l options lists the crontab file for the invoking user.
This article will discuss using a Cron type system, as used on Unix and Linux systems, to bring the flexibility, scalability and a need for more out of a task automation tool, to the Win32 environment.
Internals: Replacing Task Scheduler with Cron
- As our dependency upon machines for various tasks grow, time becomes an integral factor that may work against us, when pressed upon deadlines. Automation of such tasks, without the need for human intervention, becomes vital to whether one is able to square away enough time to complete more and more tasks with little help from human hands.
Task Scheduler, which comes bundled with Windows attempts to make automation of tasks effortless. Unfortunately, it is not very configurable and basic in what it is capable of.
On Unix and Linux systems, Cron is what is used for task scheduling. This scheduler is very configurable, and is capable of well more then its Windows counterpart.
This article will discuss using a Cron type system, as used on Unix and Linux systems, to bring the flexibility, scalability and a need for more out of a task automation tool, to the Win32 environment.
Tools:
Pycron from kalab.com
Install the product and make sure to install it as a service (default option on the last dialog box of the installer) if your Win32 operating system supports this.
Then click Start->Run->services.msc (hit enter)
Scroll down to and highlight Task Scheduler->right click->Properties->Toggle to Manual->hit Stop->then Apply->OK
Then scroll up to Python Cron Service->highlight->right click->Properties->Toggle to Automatic->Apply->OK
We will be working with a file called crontab.txt for all of the scheduled entries. This file must be created in the Pycron Program directory which is located in the pycron folder under the Program Files folder.
Create a new file called crontab.txt in the Pycron Program Directory and put this in to it
* * * * * replace replace
Save your file.
Now launch the crontab editor (Start->Programs->Pycron->Pycron CronTab Editor)
By default it will load up the contents of the crontab.txt file in the Pycron Program Directory.
Screenshot
The parameters of a crontab entry from left to right are as follows.
0-59 - Minute
0-23 - Hour
1-31 - Day
1-12 - Month
0-6 - Day of the week (0 For Mon, and 6 for Sunday)
Command/Application to execute
Parameter to the application/command.
entry:
Minute Hour Day Month Day_of_the_week Command Parameter
Note:
* is a wildcard and matches all values
/ is every (ex: every 10 minutes = */10) (new in this Win32 version)
, is execute each value (ex: every 10 minutes = 0,10,20,30,40,50)
- is to execute each value in the range (ex: from 1st (:01) to 10th (:10) minute = 1-10)
Double click the 1st entry of “ * * * * replace replace” to edit the entry.
Screenshot
For an example, we will run defrag on every Friday at 11:00 (23:00) PM against the C:\ volume.
On the Command line hit Browse, and navigate to your System32 Folder inside your Windows folder and double click on defrag.exe
On the Parameter line enter in c:
Always run a Test Execution to make sure your command is valid. If all was successful, you will see your command/application run and a kick back message of Successful will be observed.
For Minute, erase the * and enter in 0
For Hour, erase the * and enter in 23
For Week Day enter in 4.
Then hit OK, File->Save.
Note: You can use the wizard to enter in values for each entry as well.
Now open up a command prompt (start->run->cmd), and type:
net start pycron
You can leave it running now, and every time you append and or change your crontab.txt, the schedule will be updated.
To add another entry using the crontab GUI, add in a * * * * * replace replace to crontab.txt on the next free line, save it, then open up crontab.txt with the GUI editor and make the desired changes on the entry by double clicking to edit.
It is recommended that every time the GUI is used to edit entries, that you observe the entry in crontab. After you become comfortable with the syntax of cron entries, there will be no need for the GUI editor.
The entry for our defrag command becomes:
0 23 * * 4 “C:\WINDOWS\System32\defrag.exe” c:
This same task can be performed with the Task Scheduler with one entry.
Let us go through another example of more complexity, which would not as easily be accomplished with the Task Scheduler.
I want to back up my work files every 3 hours, from Monday through Friday, between the hours of 9AM to 6PM, for all the months of the year. The work folder is C:\WORK and the backup folder is C:\BACKUP.
Open up crontab.txt and on the next free line, enter in * * * * * replace replace, then save it.
Open up the crontab editor and import crontab.txt. Double click the “* * * * replace replace” entry.
For Command, browse to xcopy located in System32 within your Windows folder.
For Parameter: C:\WORK\* C:\BACKUP /Y
For Minute: 0
For Hour: 9-18/3
For Day: *
For Month: *
For Week Day: 0-4
Click OK->File->Save.
The entry for this task as reflected in our crontab.txt becomes
0 9-18/3 * * 0-4 “C:\WINDOWS\System32\xcopy.exe” C:\WORK\* C:\BACKUP /Y
If we were to schedule the above example with the Task Scheduler that comes with windows, then a separate entry for every 3rd hour mark in terms of time (AM/PM) between the aforementioned times would have to be entered, for the task.
Note: Cron can work with your own written batch/script files as well.
Note: You can view other examples in crontab.sample, located in the pycron program directory.
As you can see, Cron has a lot more to offer then the Task Scheduler. Not to say that the Windows application is not useable, but for those scenarios where you need the ability to be flexible, and configurable without all the extra headaches, then this is the ideal replacement for you. It proves to be much more efficient as well in practice.
Further Reading:
Cron Help Guide at linuxhelp.net
Pycron Home
Scripts in /etc/cron.daily run each day from 4:02 to 0:02. I want do this so that updatedb (started by slocate.cron) finishes before people start their workday. My quesiton isn't how, but whether this will create any problems.
Does anyone see any problems with running cron.daily at 2 minutes after midnight instead of 2 minutes after 4?
The tasks that run are mostly cleaning up log files and deleting old mail. This is Red Hat EL. The daily tasks are all defaults. (ls /etc/cron.daily returns: 00-logwatch 00webalizer certwatch logrotate makewhatis.cron prelink rpm slocate.cron tetex.cron tmpwatch).
Thanks in advance!===
Originally Posted by Tim65Does anyone see any problems with running cron.daily at 2 minutes after midnight instead of 2 minutes after 4?
This should be no problem.
However: if you need to apply any patches / security fixes to cron in the future, you will want to confirm that your changes weren't overwritten.===
n.yaghoobi.s : Thanks. I know how to change it - I was just wondering if anyone thought it was a bad idea.
anomie : Thanks. Good point about confirming the change doesn't get undone by patches. I'm going to make the change. If I ever do discover a problem caused by this change, I'll be sure to look up this thread and post the info here.
There are several special entries, some which are just shortcuts, that you can use instead of specifying the full cron entry. The most useful of these is probably @reboot which allows you to run a command each time the computer gets reboot. You can alert yourself when server is back online after a reboot. Also becomes useful if you want to run certain services or commands at start up. The complete list of special entries are:
Entry Description Equivalent To @reboot Run once, at startup. None @monthlyRun once a month 0 0 1 * * @weekly Run once a week 0 0 * * 0 @daily Run once a day 0 0 * * * @midnight (same as @daily) 0 0 * * * @hourly Run once an hour 0 * * * * The most useful again is @reboot. Use it to notify you when your server gets rebooted!
Users are permitted to use crontab if their names appear in the file /usr/lib/cron/cron.allow. If that file does not exist, the file /usr/lib/cron/cron.deny is checked to determine if the user should be denied access to crontab. If neither file exists, only a process with appropriate privileges is allowed to submit a job. If only cron.deny exists and is empty, global usage is permitted. The cron.allow and cron.deny files consist of one user name per line.
This can be accomplished by either listing users permitted to use the command in the file /var/spool/cron/cron.allow and the /var/spool/cron/at.allow or in the list of user not permitted to access the command in the file /var/spool/cron/cron.deny
A very god article with a lot of examples
[ian@attic4 ~]$ cat ./runclock3.sh #!/bin/bash runtime=${1:-10m} mypid=$$ # Run xclock in background xclock& clockpid=$! echo "My PID=$mypid. Clock's PID=$clockpid" ps -f $clockpid #Sleep for the specified time. sleep $runtime kill -s SIGTERM $clockpid echo "All done"
Listing 5 shows what happens when you execute
runclock3.sh. The finalkillcommand confirms that the xclock process (PID 9285) was, indeed, terminated.
Listing 5. Verifying the termination of child processes
[ian@attic4 ~]$ ./runclock3.sh 5s My PID=9284. Clock's PID=9285 UID PID PPID C STIME TTY STAT TIME CMD ian 9285 9284 0 22:14 pts/1 S+ 0:00 xclock All done [ian@attic4 ~]$ kill -0 9285 bash: kill: (9285) - No such process
If you omit the signal specification, thenSIGTERMis the default signal. TheSIGpart of a signal name is optional. Instead of using-sand a signal name, you can just prefix the signal number with a-, so the four forms shown in Listing 6 are equivalent ways of killing process 9285. Note that the special value-0, as used in Listing 4 above, tests whether a signal could be sent to a process.Listing 6. Ways to specify signals with the kill command
kill -s SIGTERM 9285 kill -s TERM 9285 kill -15 9285 kill 9285
If you need just a one-shot timer to drive an application, such as you have just seen here, you might consider the
timeoutcommand, which is part of the AppleTalk networking package (Netatalk). You may need to install this package (see Resources below for details), since most installations do not include it automatically.You now have the basic tools to run a process for a fixed amount of time. Before going deeper into signal handling, let's consider how to handle other termination requirements, such as repetitively capturing information for a finite time, terminating when a file becomes a certain size, or terminating when a file contains a particular string. This kind of work is best done using a loop, such as
for,while, oruntil, with the loop executed repeatedly with some built-in delay provided by thesleepcommand. If you need finer granularity than seconds, you can also use theusleepcommand.You can add a second hand to the clock, and you can customize colors. Use the
showrgbcommand to explore available color names. Suppose you use the commandxclock -bg Thistle -update 1&to start a clock with a second hand, and a Thistle-colored background.Now you can use a loop with what you have learned already to capture images of the clock face every second and then combine the images to make an animated GIF image. Listing 7 shows how to use the
xwininfocommand to find the window id for thexclockcommand. Then use ImageMagick command-line tools to capture 60 clock face images at one-second intervals (see Resources for details on ImageMagick). And finally combine these into an infinitely looping animated GIF file that is 50% of the dimensions of the original clock.
Listing 7. Capturing images one second apart
[ian@attic4 ~]$ cat getclock.sh #!/bin/bash windowid=$(xwininfo -name "xclock"| grep '"xclock"' | awk '{ print $4 }') sleep 5 for n in `seq 10 69`; do import -frame -window $windowid clock$n.gif& sleep 1s # usleep 998000 done convert -resize 50% -loop 0 -delay 100 clock?[0-9].gif clocktick.gif [ian@attic4 ~]$ ./getclock.sh [ian@attic4 ~]$ file clocktick.gif clocktick.gif: GIF image data, version 89a, 87 x 96
Timing of this type is always subject to some variation, so the
importcommand to grab the clock image is run in the background, leaving the main shell free to keep time. Nevertheless, some drift is likely to occur because it does take a finite amount of time to launch each subshell for the background processing. This example also builds in a 5-second delay at the start to allow the shell script to be started and then give you time to click on the clock to bring it to the foreground. Even with these caveats, some of my runs resulted in one missed tick and an extra copy of the starting tick because the script took slightly over 60 seconds to run. One way around this problem would be to use theusleepcommand with a number of microseconds that is enough less than one second to account for the overhead, as shown by the commented line in the script. If all goes as planned, your output image should be something like that in Figure 2.
Figure 2. A ticking xclock
This example shows you how to take a fixed number of snapshots of some system condition at regular intervals. Using the techniques here, you can take snapshots of other conditions. You might want to check the size of an output file to ensure it does not pass some limit, or check whether a file contains a certain message, or check system status using a command such as
vmstat. Your needs and your imagination are the only limits.If you run the
getclock.shscript of Listing 7 yourself, and you close the clock window while the script is running, the script will continue to run but will print error messages each time it attempts to take a snapshot of the clock window. Similarly, if you run therunclock3.shscript of Listing 4, and press Ctrl-c in the terminal window where the script is running, the script will immediately terminate without shutting down the clock. To solve these problems, your script needs to be able to catch or trap some of the signals discussed in Terminating a child process.If you execute
runclock3.shin the background and run theps -fcommand while it is running, you will see output similar to Listing 8.
Listing 8. Process information for runclock3.sh
[ian@attic4 ~]$ ./runclock3.sh 20s& [1] 10101 [ian@attic4 ~]$ My PID=10101. Clock's PID=10102 UID PID PPID C STIME TTY STAT TIME CMD ian 10102 10101 0 06:37 pts/1 S 0:00 xclock ps -f UID PID PPID C STIME TTY TIME CMD ian 4598 12455 0 Jul29 pts/1 00:00:00 bash ian 10101 4598 0 06:37 pts/1 00:00:00 /bin/bash ./runclock3.sh 20s ian 10102 10101 0 06:37 pts/1 00:00:00 xclock ian 10104 10101 0 06:37 pts/1 00:00:00 sleep 20s ian 10105 4598 0 06:37 pts/1 00:00:00 ps -f [ian@attic4 ~]$ All done [1]+ Done ./runclock3.sh 20s
Note that the
ps -foutput has three entries related to the runclock3.sh process (PID 10101). In particular, thesleepcommand is running as a separate process. One way to handle premature death of the xclock process or the use of Ctrl-c to terminate the running script is to catch these signals and then use thekillcommand to kill thesleepcommand.There are many ways to accomplish the task of determining the process for the sleep command. Listing 9 shows the latest version of our script,
runclock4.sh. Note the following points:
- The
sleepcommand is explicitly run in the background.- The
waitcommand is used to wait for termination of thesleepcommand.- The first
trapcommand causes thestopsleepfunction to be run whenever a SIGCHLD, SIGINT, or SIGTERM signal is received. The PID of the sleeper process is passed as a parameter.- The
stopsleepfunction is run as the result of a signal. It prints a status message and sends thesleepcommand a SIGINT signal.- When the
sleepcommand terminates, for whatever reason, thewaitcommand is satisfied. Traps are then cleared, and thexclockcommand is terminated.
Listing 9. Trapping signals with runclock4.sh
[ian@attic4 ~]$ cat runclock4.sh #!/bin/bash stopsleep() { sleeppid=$1 echo "$(date +'%T') Awaken $sleeppid!" kill -s SIGINT $sleeppid >/dev/null 2>&1 } runtime=${1:-10m} mypid=$$ # Enable immediate notification of SIGCHLD set -bm # Run xclock in background xclock& clockpid=$! #Sleep for the specified time. sleep $runtime& sleeppid=$! echo "$(date +'%T') My PID=$mypid. Clock's PID=$clockpid sleep PID=$sleeppid" # Set a trap trap 'stopsleep $sleeppid' CHLD INT TERM # Wait for sleeper to awaken wait $sleeppid # Disable traps trap SIGCHLD trap SIGINT trap SIGTERM # Clean up child (if still running) echo "$(date +'%T') terminating" kill -s SIGTERM $clockpid >/dev/null 2>&1 && echo "$(date +'%T') Stopping $clockpid" echo "$(date +'%T') All done"
Listing 10 shows the output from running
runclock4.shthree times. The first time, everything runs to its natural completion. The second time, thexclockis prematurely closed. And the third time, the shell script is interrupted with Ctrl-c.
Listing 10. Stopping runclock4.sh in different ways
[ian@attic4 ~]$ ./runclock4.sh 20s 09:09:39 My PID=11637. Clock's PID=11638 sleep PID=11639 09:09:59 Awaken 11639! 09:09:59 terminating 09:09:59 Stopping 11638 09:09:59 All done [ian@attic4 ~]$ ./runclock4.sh 20s 09:10:08 My PID=11648. Clock's PID=11649 sleep PID=11650 09:10:12 Awaken 11650! 09:10:12 Awaken 11650! [2]+ Interrupt sleep $runtime 09:10:12 terminating 09:10:12 All done [ian@attic4 ~]$ ./runclock4.sh 20s 09:10:19 My PID=11659. Clock's PID=11660 sleep PID=11661 09:10:22 Awaken 11661! 09:10:22 Awaken 11661! 09:10:22 Awaken 11661! [2]+ Interrupt sleep $runtime 09:10:22 terminating 09:10:22 Stopping 11660 ./runclock4.sh: line 31: 11660 Terminated xclock 09:10:22 All done
Note how many times the
stopsleepfunction is called as evidenced by the "Awaken" messages. If you are not sure why, you might try making a separate copy of this function for each interrupt type that you catch and see what causes the extra calls.You will also note that some job control messages tell you about termination of the
xclockcommand and interrupting thesleepcommand. When you run a job in the background with default bash terminal settings, bash normally catches SIGCHLD signals and prints a message after the next terminal output line is printed. Theset -bmcommand in the script tells bash to report SIGCHLD signals immediately and to enable job control monitoring, The alarm clock example in the next section shows you how to suppress these messages.Our final exercise returns to the original problem that motivated this article: how to record a radio program. We will actually build an alarm clock. If your laws allow recording of such material for your proposed use, you can build a recorder instead by adding a program such as
vsound.For this exercise, we will use the GNOME rhythmbox application to illustrate some additional points. Even if you use another media player, this discussion should still be useful.
An alarm clock could make any kind of noise you want, including playing your own CDs, or MP3 files. In central North Carolina, we have a radio station, WCPE, that broadcasts classical music 24 hours a day. In addition to broadcasting, WCPE also streams over the Internet in several formats, including Ogg Vorbis. Pick your own streaming source if you prefer something else.
To start rhythmbox from an X Windows terminal session playing the WCPE Ogg Vorbis stream, you use the command shown in Listing 11.
Listing 11. Starting rhythmbox with the WCPE Ogg Vorbis stream
rhythmbox --play http://audio-ogg.ibiblio.org:8000/wcpe.ogg
The first interesting point about
rhythmboxis that the running program can respond to commands, including a command to terminate. So you don't need to use thekillcommand to terminate it, although you still could if you wanted to.The second point is that most media players, like the clock that we have used in the earlier examples, need a graphical display. Normally, you run commands with the
cronandatfacilities at some point when you may not be around, so the usual assumption is that these scheduled jobs do not have access to a display. Therhythmboxcommand allows you to specify a display to use. You probably need to be logged on, even if your screen is locked, but you can explore those variations for yourself. Listing 12 shows thealarmclock.shscript that you can use for the basis of your alarm clock. It takes a single parameter, which specifies the amount of time to run for, with a default of one hour.
Listing 12. The alarm clock - alarmclock.sh
[ian@attic4 ~]$ cat alarmclock.sh #!/bin/bash cleanup () { mypid=$1 echo "$(date +'%T') Finding child pids" ps -eo ppid=,pid=,cmd= --no-heading | grep "^ *$mypid" ps $playerpid >/dev/null 2>&1 && { echo "$(date +'%T') Killing rhythmbox"; rhythmbox --display :0.0 -quit; echo "$(date +'%T') Killing rhythmbox done"; } } stopsleep() { sleeppid=$1 echo "$(date +'%T') stopping $sleeppid" set +bm kill $sleeppid >/dev/null 2>&1 } runtime=${1:-1h} mypid=$$ set -bm rhythmbox --display :0.0 --play http://audio-ogg.ibiblio.org:8000/wcpe.ogg& playerpid=$! sleep $runtime& >/dev/null 2>&1 sleeppid=$! echo "$(date +'%T') mypid=$mypid player pid=$playerpid sleeppid=$sleeppid" trap 'stopsleep $sleeppid' CHLD INT TERM wait $sleeppid echo "$(date +'%T') terminating" trap SIGCHLD trap SIGINT trap SIGTERM cleanup $mypid final wait
Note the use of
set +bmin thestopsleepfunction to reset the job control settings and suppress the messages that you saw earlier withrunclock4.shListing 13 shows an example
crontabthat will run the alarm from 6 a.m. to 7 a.m. each weekday (Monday to Friday) and from 7 a.m. for two hours each Saturday and from 8:30 a.m. for an hour and a half each Sunday.
Listing 13. Sample crontab to run your alarm clock
0 6 * * 1-6 /home/ian/alarmclock.sh 1h 0 7 * * 7 /home/ian/alarmclock.sh 2h 30 8 * * 0 /home/ian/alarmclock.sh 90m
Refer to our previous tip Job scheduling with cron and at to learn how to set your own crontab for your new alarm clock.
In more complex tasks, you may have several child processes. The cleanup routine shows how to use the
pscommand to find the children of your script process. You can extend the idea to loop through an arbitrary set of children and terminate each one.If you'd like to know more about administrative tasks in Linux, read the tutorial "LPI exam 102 prep: Administrative tasks,", or see the other Resources below. Don't forget to rate this page and let us know what other tips you'd like to see.
Learn
- This tip expands on our previous tip "Job scheduling with cron and at" (developerWorks, Jul 2007), which introduces you to scheduling jobs on Linux.
- See all Linux tips on developerWorks.
Date: Sat, 14 Sep 1996 19:50:55 -0400 (EDT)
From: Bill Duncan <bduncan@beachnet.org>
Subject: find tip...
Hi Jim Murphy,
Saw your "find" tip in issue #9, and thought you might like a quicker method. I don't know about other distributions, but Slackware and Redhat come with the GNU versions of locate(1) and updatedb(1) which use an index to find the files you want. The updatedb(1) program should be run once a night from the crontab facility. To ignore certain sub-directories (like your /cdrom) use the following syntax for the crontab file:
41 5 * * * updatedb --prunepaths="/tmp /var /proc /cdrom" > /dev/null 2>&1This would run every morning at 5:41am, and update the database with filenames from everywhere but the subdirectories (and those below) the ones listed.
Common Problems/Questions and Solutions/Answers:
Q: I edited the crontab file but the commands still don't get executed.
A: Be sure user is not editing the crontab file directly with a simple text editor such as vi. Use crontab -e which will invoke
the vi editor and then signal cron that changes have been made. Cron will only read the crontab file when the daemon
is started, so if crontab has been edited directly, cron will need to be killed, /etc/cron.d/FIFO removed, and the cron daemon
restarted in order to recover the situation.'''Q: I deleted all my crontab entries using crontab -e but crontab -l shows that they are still there.'''
A: Use crontab -r to remove an entire crontab file. Crontab -e does not know what to do with empty files,
so it does not update any changes.Q: Can I use my **** editor ?
A: Yes, by setting the environment variable EDITOR to ****.
Q: Why do I receive email when my cron job dies?
A: Because there is no standard output for it to write to. To avoid this, redirect the output of the command to a
device (/dev/console, /dev/null) or a file.Q: If I have a job that is running and my system goes down, will that job complete once the system is brought back up?
A: No, the job will not run again or pick up where it left off.
Q: If a job is scheduled to run at a time when the system is down, will that job run once the system is brought back up?
A: No, the job will not be executed once the system comes back up.
Q: How can I check if my cron is running correctly ?
A: Add the entry * * * * * date > /dev/console to your crontab file. It should print the date in the console every minute.
Q: How can I regulate who can use the cron.
A: The file /var/spool/cron/cron.allow can be used to regulate who can submit cron jobs.If /var/spool/cron/cron.allow does not exist, then crontab checks /var/spool/cron/cron.deny to see who should not be
allowed to submit jobs.If both files are missing only root can run cron jobs.
TROUBLESHOOTING CRON
If a user is experiencing a problem with cron, ask the user the following few questions to help debug the problem.
1. Is the cron daemon running?
#ps -ef |grep cron2. Is there any cron.allow/deny file?
#ls -lt /etc/cron*3. Is it the root crontab or a non-su crontab?
#crontab -e "USER NAME"4. If you are calling a script through crontab, does the script run from the command line?
Run the script at the command line and look for errors5. Check that the first 5 fields of an entry are VALID or NOT commented out.
(minute, hours, day of the month, month and weekday)6. Check for crontab related patches.
(check with sunsolve and the solaris version installed on the system for exact patch match)7. Check for recommended and security related patches?
(recommend to the customer to install all recommended and security patches relevant to the OS installed)8. How did you edit crontab?
#crontab -e "user name"9. How did you stop/kill the cron daemon?
#/etc/init.d/cron stop and start
Many times admins forget the field order of the crontab file and alway reference the man pages over-and-over. Make your life easy. Just put the field definitions in your crontab file and comment (#) the lines out so the crontab file ignores it. # minute (0-59), # | hour (0-23), # | | day of the month (1-31), # | | | month of the year (1-12), # | | | | day of the week (0-6 with 0=Sunday). # | | | | | commands 3 2 * * 0,6 /some/command/to/run 3 2 * * 1-5 /another/command/to/run
Users are permitted to use crontab if their names appear in the file /usr/lib/cron/cron.allow. If that file does not exist, the file /usr/lib/cron/cron.deny is checked to determine if the user should be denied access to crontab. If neither file exists, only a process with appropriate privileges is allowed to submit a job. If only cron.deny exists and is empty, global usage is permitted. The cron.allow and cron.deny files consist of one user name per line.
This can be accomplished by either listing users permitted to use the command in the file /var/spool/cron/cron.allow and the /var/spool/cron/at.allow or in the list of user not permitted to access the command in the file /var/spool/cron/cron.deny.
Dru Lavigne 09/27/2000
cron - Wikipedia, the free encyclopedia
InformIT Red Hat Linux 7 Unleashed Scheduling Tasks with cron and at Jobs
Introduction to UNIX cron and at Utilities by by John Raithel This article first appeared in Linux Journal
cron.pm Cron - cron-like scheduler for Perl subroutines
How to Use the Cron and Crontab commands
UNIX Shell Script Tutorials & Reference
Howtos Remote backup using ssh, tar and cron
LJ Take Command cron: Job Scheduler by Michael S. Keller
Have you ever wandered near your Linux box in the middle of the night, only to discover the hard disk working furiously? If you have, or just want a way for some task to occur at regular intervals, cron is the answer.
Debian GNU-Linux -- anacron a cron-like program that does not assume that the system is running continuously.
Anacron (like `anac(h)ronistic') is a periodic command scheduler. It executes commands at intervals specified in days. Unlike cron, it does not assume that the system is running continuously. It can therefore be used to control the execution of daily, weekly and monthly jobs (or anything with a period of n days), on systems that don't run 24 hours a day. When installed and configured properly, Anacron will make sure that the commands are run at the specified intervals as closely as machine-uptime permits.
This package is pre-configured to execute the daily jobs of the Debian system. You should install this program if your system isn't powered on 24 hours a day to make sure the maintenance jobs of other Debian packages are executed each day.
crontab command creates, lists or edits the file containing control statements to be interpreted by the cron command (cron table). Each statement consists of a time pattern and a command. The cron program reads your crontab file and executes the commands at the time specified in the time patterns. The commands are usually executed by a Bourne shell (sh).
The crontab command reads a file or the standard input to a directory that contains all users' crontab files. You can use crontab to remove your crontab file or display it. You cannot access other users' crontab files in the crontab directory.
COMMAND FORMAT
Following is the general format of the crontab command.
crontab [ file ]
crontab -e [ username ]
crontab -l [ username ]
crontab -r [ username ]
Options
The following options may be used to control how crontab functions.
| -e | Edit your crontab file using the editor defined by the EDITOR variable. |
| -r | Removes your current crontab file. If username is specified then remove that user's crontab file. Only root can remove other users' crontab files. |
| -l | List the contents of your current crontab file. |
Crontab File Format
The crontab file contains lines that consist of six fields separated by blanks (tabs or spaces). The first five fields are integers that specify the time the command is to be executed by cron. The following table defines the ranges and meanings of the first five fields.
|
|
||
| Field | Range | Meaning |
|---|---|---|
|
|
||
| 1 | 0-59 | Minutes |
| 2 | 0-23 | Hours (Midnight is 0, 11 P.M. is 23) |
| 3 | 1-31 | Day of Month |
| 4 | 1-12 | Month of the Year |
| 5 | 0-6 | Day of the Week (Sunday is 0, Saturday is 6) |
|
|
||
Each field can contain an integer, a range, a list, or an asterisk (*). The integers specify exact times. The ranges specify a range of times. A list consists of integers and ranges. The asterisk (*) indicates all legal values (all possible times).
The following examples illustrate the format of typical crontab time patterns.
|
|
|
| Time Pattern | Description |
|---|---|
|
|
|
| 0 0 * * 5 | Run the command only on Thursday at midnight. |
| 0 6 1,15 * 1 | Run the command at 6 a.m. on the first and fifteenth of each month and every Monday. |
| 00,30 7-20 * * * | Run the command every 30 minutes from 7 a.m. to 8 p.m. every day. |
|
|
|
NOTE:
The day of the week and day of the month fields are interpreted separately if both are defined. To specify days to run by only one field, the other field must be set to an asterisk (*). In this case the asterisk means that no times are specified.
The sixth field contains the command that is executed by cron at the specified times. The command string is terminated by a new-line or a percent sign (%). Any text following the percent sign is sent to the command as standard input. The percent sign can be escaped by preceding it with a backslash (\%).
A line beginning with a # sign is a comment.
Each command in a crontab file is executed via the shell. The shell is invoked from your HOME directory (defined by $HOME variable). If you wish to have your (dot) .profile executed, you must specify so in the crontab file. For example,
0 0 * * 1 . ./.profile ; databaseclnup
would cause the shell started by cron to execute your .profile, then execute the program databaseclnup. If you do not have your own .profile executed to set up your environment, cron supplies a default environment. Your HOME, LOGNAME, SHELL, and PATH variables are set. The HOME and LOGNAME are set appropriately for your login. SHELL is set to /bin/sh and PATH is set to :/bin:/usr/bin:/usr/lbin.
NOTE:
Remember not to have any read commands in your .profile which prompt for input. This causes problems when the cron job executes.
Command Output
If you do not redirect the standard output and standard error of a command executed from your crontab file, the output is mailed to you.
Access
To use the crontab command you must have access permission. Your system administrator can make the crontab command available to all users, specific users, or no users. Two files are used to control who can and cannot access the command. The cron.allow file contains a list of all users who are allowed to use crontab. The cron.deny file contains a list of all users who are denied access to crontab. If the cron.allow file exists but is empty, then all users can use the crontab command. If neither file exists, then no users other than the super-user can use crontab.
Displaying your crontab
If you have a crontab file in the system crontab area, you can list it by typing crontab -l. If you do not have a crontab file, crontab returns the following message:
crontab: can't open your crontab file.
DIAGNOSTICS AND BUGS
The crontab command will complain about various syntax errors and time patterns not being in the valid range.
CAUTION:
If you type crontab and press Return without a filename, the standard input is read as the new crontab entries. Therefore, if you inadvertently enter crontab this way and you want to exit without destroying the contents of your current crontab file, press the Del key. Do not press the Ctrl-D key; if you do, your crontab file will only contain what you have currently typed.
Related Commands
| /usr/sbin/cron.d | The main directory for the cron process. |
| /usr/sbin/cron.d/log | Accounting information for cron processing. |
| /usr/sbin/cron.d/crontab.allow | A file containing a list of users allowed to use crontab. |
| /usr/sbin/cron.d/crontab.deny | A file containing a list of users not allowed to use crontab. |
| /usr/spool/cron/crontabs | Location of crontab text to be executed. |
Crontab supports two files:
/etc/cron.allow /etc/cron.deny
If cron.allow exists then you MUST be listed in it to use crontab (so make sure all the system accounts like root are listed), this is very effective for limiting cron to a small number of users. If cron allow does not exists, then cron.deny is checked and if it exists then you will not be allowed to use crontab unless you are listed ("locked out")
In both cases users are listed one per line, so you can use something like:
cat /etc/passwd | cut -d":" -f 1 | fgrep -v `cat cron.deny` > /etc/cron.allow
To populate it and then delete all system accounts and unnnessary user accounts.
I assume you are on a Linux system. Then, you have a small syntax error in viewing other users crontabs, try "crontab -l -u username" instead.
Here is how it works: Two config files, /etc/cron.deny and /etc/cron.allow (on SuSE systems these files are /var/spool/cron.deny and .../allow), specify who can use crontab.
If the allow file exists, then it contains a list of all users that may submit crontabs, one per line. No unlisted user can invoke the crontab command. If the allow file does not exist, then the deny file is checked.
If neither the allow file nor the deny file exists, only root can submit crontabs.
This seems to be your case, so you should create one of these files ... on my system I have a deny file just containing user "guest", so all others are allowed.One caveat: this access control is implemented by crontab, not by cron. If a user manages to put a crontab file into the appropriate directory by other means, cron will blindly execute ...
[from the book "Linux Administration Handbook" by Nemeth/Snyder/Hein and validated locally here]
You can control access to the crontab command by using two files in the /etc/cron.d directory: cron.deny and cron.allow. These files permit only specified users to perform the crontab command tasks such as creating, editing, displaying, or removing their own crontab files.
The cron.deny and cron.allow files consist of a list of user names, one per line. These access control files work together as follows:
- If cron.allow exists, only the users listed in this file can create, edit, display, or remove crontab files.
- If cron.allow does not exist, all users can submit crontab files, except for users listed in cron.deny.
- If neither cron.allow nor cron.deny exists, superuser privileges are required to run the crontab command.
Superuser privileges are required to edit or create the cron.deny and cron.allow files.
The cron.deny file, created during SunOS software installation, contains the following user names:
daemon
bin
smtp
nuucp
listen
nobody
noaccessNone of the user names in the default cron.deny file can access the crontab command. You can edit this file to add other user names that will be denied access to the crontab command.
No default cron.allow file is supplied. So, after Solaris software installation, all users (except the ones listed in the default cron.deny file) can access the crontab command. If you create a cron.allow file, only these users can access the crontab command.
To verify if a specific user can access crontab, use the crontab -l command while you are logged into the user account. $ crontab -l
If the user can access crontab, and already has created a crontab file, the file is displayed. Otherwise, if the user can access crontab but no crontab file exists, a message such as the following is displayed: crontab: can't open your crontab file
This user either is listed in cron.allow (if the file exists), or the user is not listed in cron.deny.
If the user cannot access the crontab command, the following message is displayed whether or not a previous crontab file exists: crontab: you are not authorized to use cron. Sorry.
This message means that either the user is not listed in cron.allow (if the file exists), or the user is listed in cron.deny.
Determining if you have crontab access is relatively easy. A Unix system administrator has two possible files to help manage the use of crontab. The administrator can explicitly give permission to specific users by entering their user identification in the file:
/etc/cron.d/cron.allowAlternatively, the administrator can let anyone use crontab and exclude specific user with the file:
/etc/cron.d/cron.denyTo determine how your system is configured, first enter the following at the command line:
more /etc/cron.d/cron.allowIf you get the message, "/etc/cron.d/cron.allow: No such file or directory" you're probably in fat city. One last step, make sure you are not specifically excluded. Go back to the command line and enter:
more /etc/cron.d/cron.denyIf the file exists and you're not included therein, skip to setup instruction. If there are entries in the cron.allow file, and you're not among the chosen few, or if you are listed in the cron.deny file, you will have to contact the administrator and tell him/her you are an upstanding citizen and would like to be able to schedule crontab jobs.
In summary, users are permitted to use crontab if their names appear in the file /etc/cron.d/cron.allow. If that file does not exist, the file /etc/cron.d/cron.deny is checked to determine if the user should be denied access to crontab. If neither file exists, only the system administrator -- or someone with root access -- is allowed to submit a job. If cron.allow does not exist and cron.deny exists but is empty, global usage is permitted. The allow/deny files consist of one user name per line.
Copyright © 1996-2009 by Dr. Nikolai Bezroukov. www.softpanorama.org was created as a service to the UN Sustainable Development Networking Programme (SDNP) in the author free time. Submit comments This document is an industrial compilation designed and created exclusively for educational use and is placed under the copyright of the Open Content License(OPL). Site uses AdSense so you need to be aware of Google privacy policy. Original materials copyright belong to respective owners. Quotes are made for educational purposes only in compliance with the fair use doctrine.
Disclaimer:
Last modified: November 17, 2009