rubenlech
By:
rubenlech

Autogenerate cron task with new server

May 24, 2017 431 views
PHP Linux Basics Linux Commands Ubuntu 16.04

Hi,

I try to create new server and add in User Data command to create new cron task.

My code:

sudo apt-get install cron
(crontab -l ; echo "* * * * * php /var/www/html/test.php") | crontab -

When I run 'nano /var/spool/cron/crontabs/root', I get :

# DO NOT EDIT THIS FILE - edit the master and reinstall.
# (- installed on Wed May 24 08:27:25 2017)
# (Cron version -- $Id: crontab.c,v 2.13 1994/01/17 03:20:37 vixie Exp $)
* * * * * php /var/www/html/test.php

Unfortunelly server doesn't run my test file.
PHP syntax in file is correct, because when I run it via browser everything work propelly.

1 Answer

@rubenlech

You shouldn't need to attempt to install cron as it's already part of the distro.

That said, try using:

echo "* * * * * php /var/www/html/test.php" | crontab

You can then confirm that the scheduled task exists by running crontab -e.

I setup a test script using the same command and it did exactly as expected.

<?php
$file   =   '/usr/local/src/test.log';
$date   =   date('Y-m-d') . PHP_EOL;

$file   =   file_put_contents( $file, $date, FILE_APPEND );

All it's doing is appending $date to a new line in test.log every minute.

After 10 minutes, the file looked like:

2017-05-24
2017-05-24
2017-05-24
2017-05-24
2017-05-24
2017-05-24
2017-05-24
2017-05-24
2017-05-24
2017-05-24

At which point I deleted the task since it was working as expected.

...

You'll need to make sure you have the CLI package installed for your PHP version. Since this is executing from the command line, that package is required.

Have another answer? Share your knowledge.