Report this

What is the reason for this report?

Autogenerate cron task with new server

Posted on May 24, 2017

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.



This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

@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.

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.