Time management on the system: "cron" and "at"

Computers have always included hardware capable of measuring the time. Any user knows this benefit, with programs that print the hour, the month, the year or even the complete calendar system.

This is a System Administrator's job; to set the correct date and time on all the systems present in the network. This precision is essential to maintain sources and development projects, e-mail transit, printing of legal works and other common tasks.

The "date" command

In Linux as for UNIX, the command for managing the date system is "date".

This command lets you know the current system date:

[root@heaven /root]# date
Thu Dec  3 09:54:34 GMT 1998
[root@heaven /root]#

This command includes a very large number of parameters, which we can see with the help option:

[root@heaven /root]# date --help
Usage: date [OPTION]... [+FORMAT]
  or:  date [OPTION] [MMDDhhmm[[CC]YY][.ss]]
Display the current time in the given FORMAT, or set the system date.

  -d, --date=STRING        display time described by STRING, not `now'
  -f, --file=DATEFILE      like --date once for each line of DATEFILE
  -r, --reference=FILE     display the last modification time of FILE
  -R, --rfc-822            output RFC-822 compliant date string
  -s, --set=STRING         set time described by STRING
  -u, --utc, --universal   print or set Coordinated Universal Time
      --help               display this help and exit
      --version            output version information and exit

FORMAT controls the output.  The only valid option for the second form
specifies Coordinated Universal Time.  Interpreted sequences are:

  %%   a literal %
  %a   locale's abbreviated weekday name (Sun..Sat)
  %A   locale's full weekday name, variable length (Sunday..Saturday)
  %b   locale's abbreviated month name (Jan..Dec)
  %B   locale's full month name, variable length (January..December)
  %c   locale's date and time (Sat Nov 04 12:02:33 EST 1989)
  %d   day of month (01..31)
  %D   date (mm/dd/yy)
  %e   day of month, blank padded ( 1..31)
  %h   same as %b
  %H   hour (00..23)
  %I   hour (01..12)
  %j   day of year (001..366)
  %k   hour ( 0..23)
  %l   hour ( 1..12)
  %m   month (01..12)
  %M   minute (00..59)
  %n   a newline
  %p   locale's AM or PM
  %r   time, 12-hour (hh:mm:ss [AP]M)
  %s   seconds since 00:00:00, Jan 1, 1970 (a GNU extension)
  %S   second (00..61)
  %t   a horizontal tab
  %T   time, 24-hour (hh:mm:ss)
  %U   week number of year with Sunday as first day of week (00..53)
  %V   week number of year with Monday as first day of week (01..52)
  %w   day of week (0..6);  0 represents Sunday
  %W   week number of year with Monday as first day of week (00..53)
  %x   locale's date representation (mm/dd/yy)
  %X   locale's time representation (%H:%M:%S)
  %y   last two digits of year (00..99)
  %Y   year (1970...)
  %z   RFC-822 style numeric timezone (-0500) (a nonstandard extension)
  %Z   time zone (e.g., EDT), or nothing if no time zone is determinable

By default, date pads numeric fields with zeroes.  GNU date recognizes
the following modifiers between `%' and a numeric directive.

  `-' (hyphen) do not pad the field
  `_' (underscore) pad the field with spaces

Report bugs to sh-utils-bugs@gnu.ai.mit.edu
[root@heaven /root]#

In fact,the use of this command is possible for printing only the specific data :

[root@heaven /root]# date +%y
98

or better :

[root@heaven /root]# date +%Y
1998

The date can also be displayed in the extended format :

[root@heaven /root]# date +%D
12/03/98

and this lets you write complete messages including the system date :

[root@heaven /root]# date "+Today is the %dth day of the month %h. The system time is exactly: %r"
Today is the 03th day of month Dec. The system time is exactly: 10:07:50 AM
[root@heaven /root]#

Linux also offers other programs for displaying the time or date:

[root@heaven /root]# cal
    December 1998
Su Mo Tu We Th Fr Sa
       1  2  3  4  5
 6  7  8  9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31

[root@heaven /root]#

Or for displaying future dates without limits:

[root@heaven /root]# cal 01 3050
    January 3050
Su Mo Tu We Th Fr Sa
       1  2  3  4  5
 6  7  8  9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31

[root@heaven /root]#

as we explained in Chapter 7.

How to change the system date

The "date" commandalso lets you change the system date. To the new date you only have to run the command including the new time in the order: month, day, hour and possibly the year if we have to change the current year.

In fact, the command "date" without a year updates the system date to the current year :

[root@heaven /root]# date
Thu Dec  3 12:05:05 GMT 1998
[root@heaven /root]# date 12031206
Thu Dec  3 12:06:00 GMT 1998
[root@heaven /root]#

By adding the year the date can be changed to any new time :

[root@heaven /root]# date 120312061997
Thu Dec  3 12:06:00 GMT 1997
[root@heaven /root]#

Linux also offers the possibility to move the date in any direction, in minutes, seconds, hours or years, using the parameter "-s".

In fact, the next command moves the system time "1 minute" forward. The remaining time variables are unchanged : "seconds", "month" and "year" :

[root@heaven /root]# date
Thu Dec  3 12:24:05 GMT 1998
[root@heaven /root]# date -s '+1 min'
Thu Dec  3 12:25:08 GMT 1998
[root@heaven /root]#

This option can be applied to any time variable:

[root@heaven /root]# date
Thu Dec  3 12:27:22 GMT 1998
[root@heaven /root]# date -s '-4 hour'
Thu Dec  3 08:27:24 GMT 1998
[root@heaven /root]#

RedHat by default doesn't update the BIOS clock as does Linux.

The system "Time Zone"

When RedHat is installed, it asks for the system Time Zone where the system is working at the time of installation. As you probably know, the world is divided into time zones that are equivalent to the 24 hour day; so, if it's 3:30 pm on Thursday in Rome, in Tokyo it will be 0:30 am on Friday the day after, while in Los Angeles it's 7:30 am still on Thursday.

The planetary time is set in relation to the UTC, Universal Time Coordinate that is equivalent to the hour in Greenwich, England.

So the time zone is GMT, Greenwich Mean Time. The zones start at GMT, GMT+0, ..., GMT+13, GMT-0, ..., GMT-12.

The United States of America has several zones: NY: 12:28 pm, Chicago: 11:28 am, Denver: 10:28 am, Los Angeles: 09:28 am, Honolulu: 07:28 am. For example, if the system is in New York we will use:

[root@heaven /root]# ll /etc/localtime
lrwxrwxrwx   1 root     root           27 Dec  1 13:50 /etc/localtime -> ../usr/share/zoneinfo/GMT-4
[root@heaven /root]#

That is four hours earlier than the London time.

To configure Time Zone you can use "setup".

All the files that represent the various time zones are listed in the directory "zoneinfo" :

[root@heaven zoneinfo]# pwd
/usr/share/zoneinfo
[root@heaven zoneinfo]# ls
Africa       Brazil       EST          GB           Hongkong     Kwajalein    NZ           Portugal     US           localtime
America      CET          EST5EDT      GMT          Iceland      Libya        NZ-CHAT      ROC          UTC          posixrules
Antarctica   CST6CDT      Egypt        GMT+0        Indian       MET          Navajo       ROK          Universal    posixtime
Arctic       Canada       Eire         GMT-0        Iran         MST          PRC          Singapore    W-SU         zone.tab
Asia         Chile        Etc          GMT0         Israel       MST7MDT      PST8PDT      SystemV      WET
Atlantic     Cuba         Europe       Greenwich    Jamaica      Mexico       Pacific      Turkey       Zulu
Australia    EET          Factory      HST          Japan        Mideast      Poland       UCT          iso3166.tab
[root@heaven zoneinfo]#

The file name GMT-4 is a symbolic link that represents the time zone and informs the system if the time must be changed. The GMT files don't change the system date. So, if instead of GMT-4 or other zones we use US/Eastern (that is, the time for the East coast), the BIOS time will be changed to forward. Therefore it's better to use GMT zones.

The file "iso3166.tab" includes a list that represents the countries in the world with two letters, while the file "zone.tab" includes the longitude and latitude of the most important cities in the world. These files can be used to better determine the time zone where the system is installed.

It's interesting to note that these zones are also included in the e-mail that goes through our system :

Received: from fep04-svc.tin.it (mta04-acc.tin.it [212.216.176.35]) by mbox.vol.it (8.8.5/8.8.5) with
          ESMTP id QAA24903 for <futuretg@tin.it>; Thu, 3 Dec 1998 16:36:22 +0100 (MET)
Received: from mail05.rapidsite.net ([207.158.192.42]) by fep04-svc.tin.it (InterMail v4.0
          201-221-105) with SMTP id
          <19981203153620.DTSR19863.fep04-svc@mail05.rapidsite.net for <futuretg@tin.it>; Thu,
          3 Dec 1998 16:36:20 +0100
Received: from caldera.com (207.179.18.1) by mail05.rapidsite.net (RS ver 1.0.2) with SMTP id 9373 for
          <gorlando@futuretg.com>; Thu, 3 Dec 1998 10:34:21 -0500 (EST)

This is the reason that you should always set up the time correctly.

The command "at"

Unix offers the possibility to run a command or a list of commands at a fixed time. For example, if we want to print a file two miinutes from now, we can use the program "at" to do this work in a very simple way :

[root@heaven /root]# at now +2 min
at lpr /etc/passwd
at <EOT
warning: commands will be executed using /bin/sh
job 1 at 1998-12-03 19:06
[root@heaven /root]#

To close the command sequence you have to press "Ctrl-D". The system activates a time procedure that will execute the command "lpr /etc/passwd" two (2) minutes after the "at" command.

In the same way we can run a command within "1 day" , "1 month" or 1 year.

The command sequence doesn't have any limits :

[root@heaven /root]# at now +5 min
at lpr -Prlaserps /etc/printcap
at <EOT
warning: commands will be executed using /bin/sh
job 2 at 1998-12-03 19:17

Now we can control the actual time for jobs that the system has in a queue :

[root@heaven /root]# at -l
2       1998-12-03 19:17 a
[root@heaven /root]#

All these jobs are saved in the directory "/var/spool/atjobs" :

[root@heaven atjobs]# pwd
/var/spool/atjobs

[root@heaven atjobs]# more a0000200e81d65
#!/bin/sh
# atrun uid=0 gid=0
# mail     root 0
umask 22
HISTSIZE=100; export HISTSIZE
HOSTNAME=heaven.futuretg.com; export HOSTNAME
LOGNAME=root; export LOGNAME
HELPPATH=/usr/openwin/help; export HELPPATH
MAIL=/var/spool/mail/root; export MAIL
LD_LIBRARY_PATH=/opt/Office50/lib; export LD_LIBRARY_PATH
HOSTTYPE=i386; export HOSTTYPE
PATH=/sbin:/usr/sbin:/bin:/usr/bin:/usr/loca/bin::/opt/bin:/usr/local/bin:/usr/X11R6/bin:/opt/kde/bin:/usr/
openwin/bin:; export PATH
KDEDIR=/opt/kde; export KDEDIR
HOME=/root; export HOME
PS1=[\\u@\\h\ \\W]\\\$\ ; export PS1
USER=root; export USER
LESSCHARSET=latin1; export LESSCHARSET
LANG=it_IT; export LANG
OSTYPE=Linux; export OSTYPE
OPENWINHOME=/usr/openwin; export OPENWINHOME
SHLVL=4; export SHLVL
cd /root || {
         echo 'Execution directory inaccessible' &2
         exit 1
}
lpr -Prlaserps /etc/printcap

[root@heaven atjobs]#

Linux also offers more power. Let's suppose that we have to run a list of commands, to do some prints and create some backup files in a tar compressed format.

To do this task, Linux offers an extension to the "at" program called "batch".

The "batch" program contains an internal algorithm that decides which job has the higher priority and chooses the job which produces a lower system workload. If we have to run a sequence of commands that we would generally send in background, it's better to use the "batch" program.

This a simple example.

The first step is to write the "batch" file that will include the command list :

[root@heaven /root]# more mybatch
lpr /etc/passwd
tar cvfz MYTAR.tgz To_Send
echo ""

If these commands must be run immediately, we don't add any parameter:

[root@heaven /root]# batch < mybatch
warning: commands will be executed using /bin/sh
job 6 at 1998-12-03 19:36
[root@heaven /root]#

The commands are executed immediately so as to have the lowest possible system workload in the system :

[root@heaven /root]# l MYTAR.tgz
MYTAR.tgz
You have new mail in /var/spool/mail/root
[root@heaven /root]#

The file is created and the system tells us, with the use of mail messages, if the batch command sequence succeeded or failed.

In fact, the mail message gives details about the job that was executed:

[root@heaven /root]# mail
Mail version 8.1 6/6/93.  Type ? for help.
"/var/spool/mail/root": 1 message 1 unread
U  1 root@heaven.futuretg  Thu Dec  3 19:36  16/428   "Output from your job        6"
&
Message 1:
From root  Thu Dec  3 19:36:39 1998
Return-Path: <root
Received: (from root@localhost)
        by heaven.futuretg.com (8.8.7/8.8.7) id TAA01446
        for root; Thu, 3 Dec 1998 19:36:39 GMT
Date: Thu, 3 Dec 1998 19:36:39 GMT
From: root <root@heaven.futuretg.com
Message-Id: <199812031936.TAA01446@heaven.futuretg.com
Subject: Output from your job        6
Status: RO

To_Send/
To_Send/IFTLinuxCourse.html
To_Send/Iour_technologies.html
 

&

Of course, we should run the "at" command for all these tasks.

The difference between the "at" and  the "batch" commands is that batch offers the maximum optimization for a list of commands, while "at" is preferable for running one command at a time.

The "cron" command

Linux also offers the System Administrator the possibility to set up timer procedures. With "cron" we can execute a system backup every day at 06:30 pm, connect to the Internet and download the page about the best place to visit for the week-end, each Friday at 5:00 pm, to download our Web magazine quarterly; in short, to to do things at specific times depending upon the task.

The main difference between the "cron" and "at" commands is that the "cron" command contains a file with the scheduling table called "/etc/crontab" that includes all the jobs and the times at which they are to be activated. The "cron" daemon checks this file and runs the jobs at the designated time.

This is a classical file :

[root@heaven /root]# more /etc/crontab
SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root

# IMPORTANT! All scripts/commands run by cron with root-privileges
# should be written with security in mind!!!
#
# A common problem is related to temporary files residing in world-writable
# directories (esp. /tmp).  As most GNU utilities (at least sort(1)) respect
# a TMPDIR environment variable it should be used!
# To support this, there are some helper functions in the cronloop hierarchy
# (currently /etc/cron.d/lib/functions), namely cronloop_mk_TMPDIR and
# cronloop_rm_TMPDIR, for handling sufficiently(?) uniq temporary directories
# (exemplary usage may be inspected in Daily/50updatedb).

# Run any at jobs every minute (ONLY if 'atd' is NOT running!)
#* * * * * root [ -x /usr/sbin/atrun ] && /usr/sbin/atrun

# run-parts
03  3  1  *  * root [ -x /usr/sbin/cronloop ] && /usr/sbin/cronloop Monthly
04  4  *  *  6 root [ -x /usr/sbin/cronloop ] && /usr/sbin/cronloop Weekly
05  5  *  *  * root [ -x /usr/sbin/cronloop ] && /usr/sbin/cronloop Daily
42  *  *  *  * root [ -x /usr/sbin/cronloop ] && /usr/sbin/cronloop Hourly

# extensions...

# e.g if you want to have locatedb be built by daemon
# (additional provision have to be taken to allow write access to the database!)
#55  5  *  *  * daemon /etc/cron.d/lib/update-locatedb

[root@heaven /root]#

The "crontab" file has the following format :

The first line of the file :

03  3  1  *  * root [ -x /usr/sbin/cronloop ] && /usr/sbin/cronloop Monthly

represents a job that will run every day at 3:03 am.

Instead, if we want to run a job each Friday at 18:30, the line will be as follows :

30  18 * * * 5

If the backup must be made every day :

30  18 * * * *

Of course if the system is down, there job won't be executed. If the system is up 24 hours a day, all the year round, it's convenient to cancel the week-end and therefore Saturday and Sunday. The line will be:

30  18 * * * 1,2,3,4,5

For setting up quarterly jobs, we have to work with the third column. For example, for downloading a page at each 15th day of the month at 9:00, the line will be :

00 9 15 * *

The "cron" daemon starts at system boot. To check if it's running we can simply do the command :

[root@heaven /root]# ps ax | grep cron
  423  ?  S    0:00 cron
[root@heaven /root]#

The System Administrator manages the "/etc/crontab" file. Unix and Linux also offer the possibility for each user to set up their own cron files called  "crontab" files.

To use this function the user must create a file with the same format as the "/etc/crontab" file and then run the command:

orlando@heaven:~ crontab mycrontab
orlando@heaven:~

Through the "crontab" command it's always possible either to display the cron jobs in the queue with the parameter "-l" (list) or remove them with the parameter "-r" (remove).

The cron functions are present in AT&T UNIX Sys V, Rel 3.

Linux also offers the System Administrator the possibility to time the system jobs. The "time" command was created for this purpose. (In DOS, the time command prints the system time. The DOS "time" is equivalent to the command "date" in UNIX/Linux.

To introduce the command, we will run the command "time" together with the "sleep" command that starts a time-out of 10 seconds:

[root@heaven /root]# time sleep 10
0.00user 0.00system 0:09.99elapsed 0%CPU (0avgtext+0avgdata 0maxresident)k
0inputs+0outputs (75major+9minor)pagefaults 0swaps
[root@heaven /root]#

As we can see the time that passed was 0.09.99, equivalent to 10 seconds.

The "time" command lets you print how many seconds, for example, it takes Netscape Communicator 4.5 to appear on the screen.

For knowing this, we run the command :

[root@heaven /root]# time -o file netscape

Please exit from the Netscape when it appears! The "-o" option writes the elapsed time to the filename specified after the "-o":

[root@heaven /root]# more file
Command exited with non-zero status 2
1.00user 0.11system 0:04.72elapsed 23%CPU (0avgtext+0avgdata 0maxresident)k
0inputs+0outputs (2203major+1576minor)pagefaults 0swaps
[root@heaven /root]#

Some operations that take some seconds in UNIX systems are immediate on Linux!

[root@heaven /root]# time --verbose cat /vmlinuz > /dev/null
        Command being timed: "cat /vmlinuz"
        User time (seconds): 0.00
        System time (seconds): 0.01
        Percent of CPU this job got: 166%
        Elapsed (wall clock) time (h:mm:ss or m:ss): 0:00.00
        Average shared text size (kbytes): 0
        Average unshared data size (kbytes): 0
        Average stack size (kbytes): 0
        Average total size (kbytes): 0
        Maximum resident set size (kbytes): 0
        Average resident set size (kbytes): 0
        Major (requiring I/O) page faults: 75
        Minor (reclaiming a frame) page faults: 9
        Voluntary context switches: 0
        Involuntary context switches: 0
        Swaps: 0
        File system inputs: 0
       File system outputs: 0
        Socket messages sent: 0
        Socket messages received: 0
        Signals delivered: 0
        Page size (bytes): 4096
        Exit status: 0
[root@heaven /root]#

Please note that the system workload was 166%!

Other System Administration commands

The commands that we have introduced in this chapter are only some of the commands that Linux offers to System Administrators.

There are also other commands.

Linux, like UNIX, has the data in the memory buffer. These data are written on the disk only when necessary. The program "sync" lets you update this buffer and the corresponding date/time. This operation is very rare, therefore it may be necessary first either to halt the system or the machine that works 365 days a year.

This is the command :

[root@heaven /root]# sync
[root@heaven /root]# sync
[root@heaven /root]# sync
[root@heaven /root]#

It's convenient to run the command two or three times to be sure that the data buffer has been written on the disk and then halt the system.

The other System Administrator jobs are to add users to the system, with the user process management, and also to manage job priority between them.

All these tasks have been explained in previous chapters. Now we only have to explain how to manage job priority between users. Linux lets you change a system job priority before the command execution or while running, so we can finish the most important system work before doing another job of secondary importance.

Let's suppose that the system is running the compilation of several components of a big project. The result of a report program for marketing has a higher priority than the program about the stock. Using the program "nice" it's possible to change the priority to the marketing task

In fact, the program "nice" without any parameters prints us the actual priority user level :

[root@heaven /root]# nice
0
[root@heaven /root]#

The nice priority ranges from the highest "-20" to the lowest priority of "19".

Observe how "nice" changes the priority of a program, allowing a higher or a lower workload depending on the request:

[root@heaven /root]# time nice --20 cat /etc/passwd /dev/null
0.00user 0.01system 0:00.00elapsed 166%CPU (0avgtext+0avgdata 0maxresident)k
0inputs+0outputs (150major+15minor)pagefaults 0swaps
[root@heaven /root]#
[root@heaven /root]#
[root@heaven /root]# time nice -19 cat /etc/passwd /dev/null
0.00user 0.00system 0:00.07elapsed 0%CPU (0avgtext+0avgdata 0maxresident)k
0inputs+0outputs (150major+15minor)pagefaults 0swaps
[root@heaven /root]#

As we can see, with priority "-20" the CPU has a workload of 166% and uses only 0.01 of the system CPU, while with the lower priority the system workload is constant and the command takes only 0.07 seconds.

The parameter "--20" moves the nice priority to "-20" and therefore changes the priority to the highest.
 

Exercises

  1. Run the "at" command to send a printer job in 3 minutes
  2. Try the batch command and a list of common frequent commands
  3. Locate your Time Zone and update it if it's wrong
  4. Move the date two years forward with the command "date -s". Afterwards reboot the system. What is the new date?
  5. Activate a cron procedure to do a weekly or daily backup
Test
  1. Where is the boot file for FreeDOS placed?
  2. What are the log daemons that start by default in Linux?
  3. What file contains the system messages?
  4. What program can be used to setup service at startup ?
  5. What are log files?
  6. What file includes the configuration for print jobs on the system?
  7. What is the goal of the programs "at" and "cron"?
  8. What is the main advantage of using the "batch" program?
  9. What does the "time" program show?
  10. What is the goal of the "nice" command?
Consult the answers

Check the Interactive Exam Cram BASE: Try the interactive cram ...
 

Internet Resources for this chapter.