Run
Run

Reputation: 57286

Linux cron task - how to add and run a cron task?

How can I run a cron task in Linux?

Following this Q&A,I have this cron task to run - just writing some info to a txt file,

// /var/www/cron.php
$myfile = fopen("cron.txt", "w") or die("Unable to open file!");
$txt = "John Doe\n";
fwrite($myfile, $txt);
$txt = "Jane Doe\n";
fwrite($myfile, $txt);
fclose($myfile);

But after adding the cron task via my terminal,

crontab -e

and then,

* * * * * /usr/bin/php /var/www/cron.php &> /dev/null

But when I open cron.txt, there is nothing in it.

Why? What have I missed?

Upvotes: 0

Views: 230

Answers (2)

Change cron.txt by full path /var/www/my_system/cron.txt

// /var/www/cron.php
$myfile = fopen("/var/www/my_system/cron.txt", "w") or die("Unable to open file!");
$txt = "John Doe\n";
fwrite($myfile, $txt);
$txt = "Jane Doe\n";
fwrite($myfile, $txt);
fclose($myfile);

Or move to directory:

chdir("/var/www/my_system");
$myfile = fopen("cron.txt", "w") or die("Unable to open file!");
$txt = "John Doe\n";
fwrite($myfile, $txt);
$txt = "Jane Doe\n";
fwrite($myfile, $txt);
fclose($myfile);

And try again.

Upvotes: 3

paulsm4
paulsm4

Reputation: 121869

I would eliminate the redirect to /dev/null until you're sure you're not getting an error message.

My guess is "permissions".

SUGGESTIONS:

  1. Execute /usr/bin/php /var/www/cron.php manually, from the command prompt, to make sure the PHP script is OK.

  2. Identify the directory "myfile.txt" is being written to.

  3. Make sure both the directory and myfile.txt are writable.

Here are a couple of links with other troubleshooting hints:

Upvotes: -1

Related Questions