mk_89
mk_89

Reputation: 2742

cron job that kills a process after 5 hours

I basically have a cron job which runs every night that updates thousands of products in my database.

The reason I run the cron job at night is because there will be less latency on the servers as not many people visit the site during this time, the cron job can pretty much run on for days without any interference.

Here is what the cron job command looks like

30 23 * * *     /usr/bin/php /var/www/ul/prices_all.php >> /var/www/ul/log/prices_all.txt

What I would like to know is would it be possible to create a cron job which kills this process after 5 hours e.g.

30 05 * * *     kill /var/www/ul/prices_all.php[process]

Upvotes: 8

Views: 12616

Answers (2)

Green Black
Green Black

Reputation: 5084

You can do this with timeout (coreutils):

30 23 * * *   timeout 18000  /usr/bin/php /var/www/ul/prices_all.php >> /var/www/ul/log/prices_all.txt

It simply sets a timeout (18000secs = 5 hours) and kills the process if it is still running after that time.

Or you can set a timeout in the php file itself:

<?php set_time_limit(18000);

Upvotes: 22

Paul Kehrer
Paul Kehrer

Reputation: 14089

Yes, you could create a cronjob that killed the process 5 hours later. There are a few decent ways to do this. For instance, you could have the first script write its pid (you can get it with getmypid()) to a file when it starts up and then have the second cron job read that pid and kill it. This would work, but is pretty inelegant.

A more elegant method would be setting an execution limit in the script itself if your PHP config allows it (ie, is not in safe mode).

Upvotes: 0

Related Questions