Running two commands sequentially in a cron job?

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.


Solution 1:

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.

Solution 2:

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.