Nitish
Nitish

Reputation: 2763

Run a cron job that prints current time in Ubuntu

I want to run a php script in every 2 minutes that prints current time in a file called data.txt. For this , I have created a file within /var/www/test/cronjob.php:

$fp = fopen('data.txt', 'w');
$ctime = date('d/m/Y h:i:s A');
fwrite($fp, $ctime);

fclose($fp);

This works nicely if I run it in my browser. To execute this file in every 2 minutes, within an interval, I write in crontab */2 * * * * /var/www/html/test/cronjob.php But its not writing anything in my data.txt file. I used THIS tutorial.

Upvotes: 1

Views: 666

Answers (1)

baao
baao

Reputation: 73271

cron needs to know how to run your script, so you need to specify it in your cron line:

*/2 * * * * /usr/bin/php /var/www/html/test/cronjob.php 1>> /dev/null 2>&1

The 1>> /dev/null 2>&1 will quite cron so that it doesn't saves logs.

You will also need to change the path to the file you want to save. It won't be saved in /var/www/html/test/ as you might be expecting, but in your users home directory, which will be ~/<your username>. To save in another directory, you will need to provide the full path:

$fp = fopen('/var/www/html/test/data.txt', 'w');

Also make sure that the user running the cronjob has permissions to write to that folder.

Upvotes: 1

Related Questions