Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running two commands sequentially in a cron job?

Tags:

sh

cron

I have two commands in a cron job like this:

mysql -xxxxxx -pyyyyyyyyyyv -hlocalhost -e "call MyFunction1";wget -N http://mywebsite.net/path/AfterMyFunction1.php 

but it seems to me that both of them are running at the same time.

How can I make the first command run and when it completes, execute the second command?

Also the AfterMyFunction1.php have javascript http requests that are not executed when I use wget. It works if I opened AfterMyFunction1.php in my webbrowser.

like image 886
medo ampir Avatar asked Mar 09 '12 18:03

medo ampir


People also ask

Does crontab run sequentially?

Yes, using ; between the commands will guarantee that all commands are run sequentially, one after the other. The execution of one command would not depend on the exit status of the previous one.

What is the use of * * * * * In cron?

It is a wildcard for every part of the cron schedule expression. So * * * * * means every minute of every hour of every day of every month and every day of the week .

Can you have multiple crontabs?

No. Each user has one crontab.

What is the difference between crontab at and batch?

While cron is used to schedule recurring tasks, the at command is used to schedule a one-time task at a specific time and the batch command is used to schedule a one-time task to be executed when the systems load average drops below 0.8.


2 Answers

If the first command is required to be completed first, you should separate them with the && operator as you would in the shell. If the first fails, the second will not run.

like image 172
vincent Avatar answered Oct 04 '22 14:10

vincent


You could use sem which is part of GNU parallel.

0 0 * * * root  sem --jobs 1 --id MyQueue mysql -xxxxxx -pyyyyyyyyyyv -hlocalhost -e "call MyFunction1" 1 0 * * * root  sem --jobs 1 --id MyQueue wget -N http://mywebsite.net/path/AfterMyFunction1.php 

This cron config will first start the mysql through sem, which will put it in a kind of queue called MyQueue. This queue will probably be empty, so the mysql is executed immediately. A minute later, the cron will start another sem which will put the wget in the same queue. With --jobs 1, sem is instructed to execute only one job at a time in that particular queue. As soon as the mysql has finished, the second sem will run the wget command. sem has plenty of options to control the queueing behaviour. For example, if you add --semaphoretimeout -60, a waiting job will simply die after 60 seconds.

The && solution is probably better, since it won't execute the second command when the first one fails. The sem solution has the advantage that you can specify different cron settings, like a different user. And it will prevent overlapping cron jobs, if the cron interval is shorter than the job duration.

like image 21
Onnonymous Avatar answered Oct 04 '22 14:10

Onnonymous