How to install cron job from php script?

I am new to cron. I learned some of the basics of cron. I can call php using the cron tab. Using the following command in / etc / crontab

10 * * * * root /usr/bin/php /var/www/PATH TO SCRIPT/email.php 

In email.php I have the following code

  #!/usr/bin/php <?php mail (" examplemail@mail.com ", "Cron Successful Public HTML!","Hello World from mycron.php!"); ?> 

For every 10 minutes I get mail. But I need to know if there is a way to invoke the cron job from php (invoke cron from php) I get some idea while surfing, but I am not able to figure out how to exactly do my job. Here is the code I used to add the job using php

  exec('echo -e "crontab -e \n2 * * * * /usr/bin/php /var/www/PATH TO THE SCRIPT/crontest1.php" '); 

It does not work for me. can anyone tell me how to call or add cron from php. so that I can send mail by executing a php file and I can change the time interval in the php file itself.

+7
source share
3 answers

From How to set cron job via PHP script Nick Clark :

This will add a script that will run every day at 9:30 a.m.

 exec('echo -e "`crontab -l`\n30 9 * * * /path/to/script" | crontab -'); 

You may have permission problems if you use this script from a web server. To get around this, I would suggest a different approach.

Here is one possible solution. Create a list of scripts to run. You can save this in a text file or in a database. Create a script to read this list and run it every minute or every 5 minutes (using cronjob). Your script should be smart enough to decide when to start the list of scripts and when to just exit.

You can do it as follows.

Other links:

Install cron job with php script

How to call cron job from php script?

+8
source

You should be able to add it directly.

 echo "2 * * * * /usr/bin/php /var/www/PATH TO THE SCRIPT/crontest1.php\n" > /etc/cron.d/username 
+1
source

Many environments do not allow you to write a text file from a php page called from the Internet. I agree that this is a security risk that cannot be taken.

I have a webpage that saves data to a MySQL table through a jQuery call to a php script. In Cron, I plan another PHP script to, each so often, to check the data in the MySQL table and perform any necessary tasks.

0
source

All Articles