Scheduling one-time events with AT from PHP script not working - php

I need to use PHP to schedule tasks for later execution on a local machine. I am avoiding cron because I do not need to repeat the task over time.
I tried
$msg="at 10am today
date > /path/path/date.txt
\x04";
shell_exec($msg); // Nope
$msg="at 10am today
date > /path/path/date.txt
".chr(4);
shell_exec($msg); // Nope
$msg=<<<EOT
at 10am today
date > /path/path/date.txt
EOT;
shell_exec($msg); // Nope
and
shell_exec('echo "date > /some/path/date.txt" | at 10am today');
That last line works when executing the script with php in Terminal but not when going to the script in my web browser (http://localhost/script.php). I've tried system too but to no success. By the way, echo shell_exec('ls /') works without problem, so I don't think it's a permission issue? Does anyone have any ideas what's wrong?
Background information: the motivation for this is that I am building a web-based interface for specifying and submitting computationally intensive simulation jobs to remote machines. My PHP script generates R and Matlab scripts from user-input, and I can SSH into those machines from PHP just fine. I just can't schedule those scripts to be executed at a later time, independent of the SSH session.

The probem is, as you suggest, on wich user execute the script. I think that the classic www-data can't use at command
Add dedicated user as normal user (adduser phpschedule);
Then change user that execute php in apache from classic www-data to phpschedule

Related

I need to run a PHP script I wrote as a task on my server

I need to run a PHP script which is scraping a website for data, and I need to run it on my VPS which has linux. I want to run it as a task so that I should be able to logout of my VPS and the script should keep running in background.
I've read about CRON job but it's more for like scheduling and repetitive tasks; but I need the PHP script only once.
Is there a way in PHP to do that? Please help, I'm just a newbie to this.
Thanks in advance! :)
I've tried it as a CRON job, but it doesn't seem to serve my exact purpose.
so I run my script like this from terminal.
php scrapethewebsite.php
and then it show this
Started scraping at 10:03:00 20-03-2019
and I can't logout or close my vps/ssh connection.
I look for
php scrapethewebsite.php
Started scraping at 10:03:00 20-03-2019
and then I should be able to logout or close my connection. And then I should be able to shutdown my PC and go for a walk..
Yes, You can do this with the screen. The screen is most of the time already installed in Linux VPS. but still, you can get by command.
apt-get install screen
Its give you the ability to have multiple screens in VPS where you can run multiple tasks at the same time.
LIke you have.
Get a screen with command.
screen -S sessionname
sessionname will be ur screen name.
and you can dispach it with command/
CTRL + A, followed by D.
then you can close your putty or any tool from via you accessing your vps.
here you go.
for more information, you can follow this link.
Screen in Linux
Run this in your SSH session, then you can click X and close it and it will still run
nohup php scrapethewebsite.php >/dev/null 2>&1 &
to check if your file is running type this command
top
you should see the php file up there and press spacebar to update the list
_____________________________________________________________________
If your php script has some error from time to time or just runs out of execution time and you want to re-run it when it closes down.. you have to create a .sh file with a while loop inside it and run nohup on it so it will re-run the php file after it errors up.
If you want to use nohup on php file that needs to re-run from time to time, then you should do the following
$ echo 'while true ; do php scrapethewebsite.php ; done > /dev/null' > ~/php_run_loop.sh
$ chmod a+x ~/php_run_loop.sh
$ nohup ~/php_run_loop.sh
NOTE: If you have an error or other problem in your php script, this will cause it to run over and over again without any limit, forever.

when crontab job reads BMP180 sensor it returns 0

I have a raspberry PI B+ as a weather station outside. Within the control box I have the PI and a heater (for protection if the temperature should go under 0°C).
I have programmed some functions in PHP and they work fine with the crontab but one.
The file that causes me nightmares should take two temperatures from two sensors and write two files (one log and one instant temperature with some other data).
I use two commands in order to do that:
$temp_ex=round(system("checktemp"),1);
$temp_el=round(system("python temp_connectivity.py"),1);
the first command runs everytime. With no problems whatsoever.
The second command, which calls:
import Adafruit_BMP.BMP085 as BMP085
sensor = BMP085.BMP085()
print '{0:0.2f}'.format(sensor.read_temperature())
works only if I run my php file with the terminal. I get the correct temperature.
When the file is used by the crontab I always get 0 (even at 20°C).
Both python and php files have execute rights. I tried both with system() and exec() commands with no luck.
Anyone that can suggest me a way out? Thank you in advance!
There was nothing wrong with the sensor or the code.
It was the crontab, or the permits spinning around this service.
I have used "crontab -e" in order to create my jobs but that was not good enough. I tried some other ways to call my script but I only managed to get it to work using:
sudo crontab -e
There was many python scripts that did not work but since they were hidden and not very important I failed to notice them failing.

sending email periodically through php script

I am working on an automatic monitoring system. I have made a .NET application which have MySQL database. For this I developed a normal ADMIN Panel where admin can log in and get necessary reports coming from various queries fired on the database. There is also a "summary Report" in the panel which is just the rough weekly summary. Now What I want is, I want this report (all text) to get sent automatically to some email "xxxxx#xxx.com" with a seven day period. I have used some PHP scripts previously to send email on submit button click. Like the one below.
<?php
if(isset($_POST['isPost']))
{
$header="From:".$_POST['customer_mail']."\r\nName:".$_POST['name']."\r\nCity:".$_PO ST['city'];
$subject = $_POST['title'];
$message="From:$_POST[customer_mail]\r\nName:$_POST[name]\r\nPhone:$_POST[city]\r\n \r\n\r\n\r\n".$_POST['details'];
$to = 'xxxxxxxxx#xxx.com';
$send_contact=mail($to,$subject,$message,$header);
if($send_contact)
{
echo "<h6 style='text-align:center;color:green'>Sent Successfully</h6>";
}
else
{
echo "<h6 style='color:red'>Error sending e-mail'</h6>";
}
}
?>
this is normal mail sending script which works fine. But for the above purpose I want, Can anyone help me to set this action periodically and automatically or point me in the right direction on how to do this. I have googled for such php script but no satisfied results.
~ Regards
You can do this with cronjobs.
A long running process which executes commands at given times / dates / intervals.
Depending on what system you are, there are different methods.
If you have the script on a webserver someone is running for you / Webhost service
Ask the system administrator to run the script with a cronjob. Or search for any help documentation if you can setup this yourself in any admin-panel. Ask your webhoster /system admin for more information.
If you have the script on your own local machine:
UNIX
Try reading about crontab on how to run the php script, or any script for that matter.
For example type crontab -e and add the line below in your crontab, the cronjob will run your script every hour:
00 * * * * /usr/local/bin/php /home/Low-pointer/myscript.php
Here is some more information if you want to play with the intervals
Windows
If you use Windows you can use scheduled tasks to run the php command.
For example add the following command to the scheduler: C:\wamp\bin\php\php.exe -f C:\wamp\www\my_script.php
You can also use web cron services (Google it) these are online services which run a page (for example on your webserver) on designated times. For free or paid.
You can use Cpanel to send schedule emails through the cronjob(if you are using it).
Once you open cpanel theere would be crontab system.
Add your current code to a file(xx.php) and add this command to crontab in cpanel ,
/usr/bin/php -q /home/public_html/xx.php
like everyone have already said you must use cronjob to make your task.
I assume you use a Linux OS as your production environment.
So you need:
1) A php endpoint ( eg. www.mywebsite.com/emailsend.php ) OR a CLI php script that when called send the email.
2) The correct crontab rule
Here below an example of a simple shell script ( mailsend.sh ) that call an endpoint using CURL and save an html file with an eventual response given by the webserver
#!/bin/bash
curl http://www.mywebsite.com/emailsend.php -o /path/to/my/mailsendreport/"$(date '+%Y-%m-%d-%H-%M-%S')".html
To add a scheduled task to cron
crontab -e
then add a rule like below
50 23 * * 6 sh /path/to/mailsend.sh
What "50 23 * * 6" means? It means that every sixth day of the week, in the 23th hour, in the minute 50 your sh script will be called, and then your web app and the email is sent.
Once I wrote a small doc about this you can see it here
Cheers
You're looking for "cron job".
Edit: Or since it sounds like you might be on Windows, "Scheduled Tasks"

cron jobs bring down the server?

I am using the paid host Hosting24 to run my website. I got a cron job which execute the following code every 1 minute.
<?php
require_once('connect.php');
for($c = 0; $c < 60; $c=$c+5)
{
// php to mysql queries SELECT/ UPDATE/ INSERT etc...
sleep(5);
}
mysql_close($my_connection);}
?>
I tried to use the for loop to allow the script to run for 1 minute. Eventually my script should run for as long as I want it to be because the server will execute it every 1 min.
However, I opened my website for a short while and then I cannot connect to it. I cannot even access my cpanel.
Is my cron job script overheating the system, so the system is down?
How should I set up my cron job script to let it run every 1 min and lasts for 1 min?
Thanks.
It's been my experience that cron jobs that need to include files should contain the full path to that file (the CLI environment can differ greatly from the environment inside the web server). Try that and see if it helps.
If not, the next thing you need to do is turn the cron job off and run it from the CLI yourself, using top to look at the process usage. See how long it takes for your cron to run.

Compare current time with 00:00:00 in php

I want to perform something in my php web service when it is midnight i.e. current time is 24:00:00 / 00:00:00
How can I do that ?
You could use localtime() in order to fetch current time of day, and then work on that using an if statement.
Eg.
$localtime = localtime();
if ($localtime[2] == 0) {
code;
}
Keep in mind that this only works on script that is continually executed (eg. index.php), if you want a script to execute regardless of whether it's currently being executed at the desired time, you need to use chron jobs.
Create a scheduled task which runs at a certain time and runs your script as:
php -f o/script.php
Use PHP Cron Jobs with cPanel
cPanel Simple Cron
you can get started with the simple cron tool built into cPanel.
1)Go to Cpanel
2)click cron job tab
3)Set time and page url for it is: https://www.yoursite.com/page.php
The command to run:
/usr/local/bin/php -f /home/(username)/public_html/page.php

Categories