I need to create an cron job with the following functionality:

The job should go to a particular directory and touch one file every 5 seconds. It should run for only 1 minute. The logic is to change the timestamp of the file.

I've come up with the following logic:

I have created the below cron job:

00-01 09 * * * /home/flexsys/test.sh

(the job will start at 9:00 and run up till 9:01)

The script contents is as follows:

        cd /home/A/B/C/
              while true
              sleep 5
              touch ABC.txt

I don't understand what to put in which condition tab. I have tried this through without the looping clause but it only touches the file once. I need to do it repeatedly until 9:01. What can I do to achieve this?


2 Answers 2

00-01 09 * * * /home/flexsys/test.sh (the job will start at 9:00 and run upto 9:01)

That is not what this means. This means the job will run at 9am and run again at 9:01. Cron has no concept of killing jobs, only starting them.

As for the while, you need to run the date command, find the number of minutes, and test if it is or isn't 00. On my system

date | cut -c12-19

returns the full time, 12:36:28. You'll need to figure out how to cut only the minutes out of the date output on your system.

Finally, you need the test command to determine if that value is equal to 0 or not.

Another option is that if your script needs to run for exactly 60 seconds, and you have to do something every five seconds, then you can just do your action a specific number of times and then exit.

The final problem you face is that the ls command on most, if not all, Unix systems does not display the timestamp down to the second. You will most likely need an external tool or a perl script to verify that your file's timestamp is being updated every five seconds. I'm not in a position to help you with that.

  • 3
    Why use cut if you can get seconds straight from date command by adding a relevant format switch? date +'%S' and you get the seconds without any further hassle.
    – Erathiel
    Commented May 14, 2015 at 14:01
  • 2
    stat will get you the timestamp. Look at the outputs for ls -l /var/log/syslog, stat --format '%y == %Y' /var/log/syslog, and TZ=UTC stat --format '%y == %Y' /var/log/syslog or for any other file. Commented May 15, 2015 at 8:52

00 09 * * * /home/flexsys/test.sh

    cd /home/A/B/C/
          @ a = 0
          while ( $a != 12 )
              sleep 5
              touch ABC.txt
              @ a = $a + 1

This will run your script only once, but it will touch your file 12 times with a 5 seconds pause between each touch. As long as 12*5 is 60, you'll have 1 minute of script runtime (unless you're on a slow filesystem, e.g. slow NFS)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .