PHP script to execute at certain times - php

Is there a simple way to have a php script execute some html at a certain times of the day?
For example i have on my home page a header and at certain times i want to be able to add something right under the header, in this case a iframe.
I know everyone mentioned cron jobs but how would this work with that? also is there an alternative? Its not available on all hosting

The idea of cron and scheudled jobs seems to run counter to what you're actually trying to do. If you want something to display (an iframe in this case) only during certain times, you can simply check the server time during each request, and opt to display it if you're within a given time period.
Something like this will produce the same effect as a cron job, with more granularity, checking the time at the exact moment the requst is made.
<!-- Your Header here -->
<?php
$hour = date('G'); // 0 .. 23
// Show our iframe between 9am and 5pm
if ($hour >= 9 && $hour <= 17) { ?>
<iframe .... ></iframe>
<?php } ?>
You can expand on the conditional statement to show the iframe multiple times per day, or have your script check whatever external condition you're looking to use to govern the display of your iframe.
Update:
Additional times or types of comparisons could be specified via something like
<?php
$hour = date('G');
$day = date('N'); // 1..7 for Monday to Sunday
if (($hour >= 5 && $hour <= 7) // 5am - 7am
|| ($hour >= 10 && $hour <= 12) // 10am - 12 noon
|| ($hour >= 15 && $hour <= 19) // 3pm - 7pm
|| ($day == 5) // Friday
) { ?>
<iframe...></iframe>
<?php } ?>
The idea of periodically adding/removing the iframe from below your header with a server-side cron/task scheduler job is far more complex than simply conditionally displaying it during each request.
Even if you have some specific task which must run, such as a periodically generated report, the actual job of displaying the results usually don't fall upon the periodic task. The PHP script responsible for showing that iframe would still query the database at the time the request is made for any new content to show, and display it if found, rather than the periodic task somehow modifying the script to include an iframe.

If you are running on Linux, then you could have a cron job.
If you are on Windows, then use Task Scheduler.
If you are in a hosted environment, you need to check to see if either is allowed.

cron on UNIX, launchd on OS X, and Task Scheduler on Windows platforms.

When you don't have access to cron jobs or scheduled tasks on your server, you can use online services such as http://pingability.com/ to hit your script at specified intervals. It is not perfect, but you can build in some kind of secret key and code that makes sure that the script doesn't get run multiple times within a certain time period. Might seem a little hacky, but I've used it on live systems to send out daily emails and it's been working fine for over a year now.

On Unix systems cron is your best bet.

Use a cron job or something similar, see f.i. cron jobs or PHP scheduler

You could add a PHP script to your crontab to automatically run the script at defined intervals. From the command line, enter crontab -e to add the entry to your crontab.

you can schedule the task as a cron job.

Related

How should I handle multiple seperate batch email 'streams'?

I have the following (simplified) batch email process set up under a Windows Server:
User performs action that requires an email be sent;
The data necessary to create the email is inserted into an SQL Server table;
Once every 6 hours, Task Scheduler calls a PHP file which goes through the table, creating and sending out each of the outstanding emails.
This works quite well, however the application owners would like certain sorts of email sent out more regularly, in this case, every 20 minutes.
My first thought was to set up another Task Scheduler entry, but that raises the issue of what happens every 6th hour, when both tasks will be run at the same time. It will also require creating another PHP file, which isn't really a problem, but is annoying.
The other alternative I considered was to set the scheduler to every 20 minutes, and incorporate the 'what do I send, and when' logic into the batch file itself - if it's 12AM, 6AM, 12PM or 6PM perform both sets of emails, otherwise just perform the 20 minute one. That does, however, require hardcoding those times, and doesn't seem like it should be the first resort.
Is there a better way to accomplish this?
After thinking about it a little bit more, I realised that I could accomplish what I wanted via the application of the PHP time() function and some modulo arithmetic:
$runTime = time(); //Set time the program was run, seconds since epoch
$modTimeHour = $runTime % 3600; //3600 seconds in an hour
$modTimeTwenty = $runTime % 1200; //1200 seconds in twenty minutes
//Task Scheduler doesn't always run exactly on the dot, so give it some leeway
if ($modTimeHour < 5 || $modTimeHour > 3595) {
//send emails - category 1
}
if ($modTimeTwenty < 5 || $modTimeTwenty > 1195) {
//send emails - category 2
}
By getting the seconds since epoch, and checking whether the modulo of the number of seconds in the time periods I'm interested in is within a certain range, I can have many different 'streams' all going out at their proper times.

Executing a query in a specific hour

I have script that run a php every minute. I want to make a variable that store the current hour everytime its runs so i can make an if() statement so when its 7pm execute the code inside.
$hour = date('H');
If($hour >= 7:00pm <= 5:00am)
{Do something that i know how to do it xD}
Please no Cron Job or similar.
date('H'); will return the current hour.
You can then use it in an if-statement.
It is hard to provide more than this as you showed very little of how and why you want to perform this check.
#Miguel
By default, PHP took the time from server where its located. You can set the default time in your common PHP file(which includes in all pages or at-least in that page, in which you wrote the code to execute).
using the below function, you can set the default time zone for your web application.
date_default_timezone_set('America/Los_Angeles');
here is the list of Timezones (http://php.net/manual/en/timezones.php), select according to your desire country/city and pass that value in the above function.
Sounds like this might be handled better via a cron. Just a thought.
You have several options, something rather alternative that might be a better solution depending on what you are trying to do, is to just setup the script to run everyday at 7PM.
This can be done via cron jobs in linux with the following command:
0 18 * * * php -q /path/to/php/script.php
This will be based on your server time and timezone. Based on your comment on Emz's post, You should know that when you track the time with php you need to realize that php.ini can change the time in php scripts as it has it's own timezone!

Create random minute cron job for a specific date and hour

I have been trying to do random cron jobs where I choose the year month date and hour but the minute is randomised.
My first attempt was to run the cron every min and then compare a random date with todays date:
I inserted a random date into a database column fake_time in the format 2014-10-26 17 rand(0,59). In the php page where I run the cron every min:
if($row["fake_time"] == date("Y-m-d H i")){
//do stuff
}
And this worked perfectly. But then I found out that I can't run the cron every min because my hostor (hostgator) wont allow me to! Have you got any ideas on how I can do this any other way?
Or should i just set it up on https://www.easycron.com/ instead?
I think you are being limited by the number of cron jobs you can run in a day, IIRC hostgator has a daily limit for basic plan. To work around this limitation, IMO, you have two choices:
Go to sleep for 60 seconds
Basically, run the cron job at the required hour every day, and check for your condition, if it is not True, then go to sleep for 60 seconds.
if($row["fake_time"] == date("Y-m-d H i")){
//do stuff
} else {
sleep(60);
}
This way, you have a single cron job, though it runs for a long while. In case you can run the cron job only daily, and you want to run at random hour as well as minute, you can change your logic and go to sleep for 3600 seconds for hourly sleeps, and then go for minutely sleeps of 60 seconds.
You might need to setup set_time_limit accordingly.
Set up easycron
In case your cron jobs are terminated abruptly because the time limit can't be set, you will need to hit using easycron service.
In this case, put the above script code in a php file, say script.php, and schedule a cronjob to hit with a get request on this script. Your command in this case will look something like
wget your.domain.com/script.php
If there are no technical problems, you can do it with your php script (no install required).
if(rand(1, 5) == 1){
// do your staff
}
If you think that the script will not be executed often enough, you can reduce the difference rand(1,3)

Update database every hour without cronjob

Alright, So users in my game have an hourly income. Each hour I have a cronjob run to check and see if it's time for them to be payed. It works and all, But I want to stop using cronjobs as much. Here's the coding. The coding works and I've done things without a cronjob before by using a timestamp and calculate if it's ready for the user to be able to do the function, but they have to be logged in for that. If the users not logged in for a day or so would still like them to get their hourly income each hour without cronjob.
Here's the coding:
<?php
$result = mysql_query("SELECT * FROM users ORDER BY id");
while($row = mysql_fetch_array($result)) {
$total_pay = $row['income'] - $row['upkeep'];
$timestamp_hour = time() + 3600;
$inactive_time = strtotime('+1 week',$row['last_login']);
if(time() > $inactive_time) {
$income_add = '';
echo '<div style="color: red;">'.$row['username'].' | <i>Inactive</i></div>';
}
elseif(time() < $inactive_time) {
$income_add = mysql_query("UPDATE users SET cash=(cash+".$total_pay."),energy=(energy+".$e_income.") WHERE id=".$row['id']."");
$update_time = mysql_query("UPDATE users SET payment=".$timestamp_hour." WHERE id=".$row['id']."");
echo '<div style="color: green;">'.$row['username'].' | <i>Active</i></div>';
$res = $income_add & $update_time;
}
}
?>
Would their be a way to do so without a cronjob?
Since everyone in the comments are saying the same thing - I would like to put in the same input with as much details as possible as to why you should leave it as a cron job.
1) Without a cron job or job that runs infinite with a sleep (which in essence is a cron job by itself) there is no PHP being done UNLESS you drive enough traffic that your script gets activated by a user visit (ie check if last run was more than current time, then activate)
2) the sole purpose of a cron job is to activate a set script on the clock X amount of determined time...
3) if you write your cron job effecive enough with enough fail safe you can have it small on ressources such as:
a) dont overload memory with large arrays
b) dont pull large amount of data and let it lock your table.
c) make your cron job select specific amount of data and terminates with it...if there is left over the cron job will activate itself and continue to do work until it catches up. Once caught up it will terminate quick and easy.
4) you have mentioned that people are paid at different times - the cron job shouldnt restrict that - it is up to your code and models to effectively check those time vs time now checks in order to update, so that the cron can do work when it is needed or sleep when it is not suppose to , as an example i can make a cron wake up every 5 mins but inside the code it can check current time vs last run time (via a select or last written log) and check if it should run or not. So with that you shouldn't believe that having a cron run on the clock will prevent different circumstances of your code to activate.
You can run this without a cron job on your server by using a monitoring service. Follow these steps:
Place your php script somewhere in your web path.
Open a free site monitoring account at http://www.montastic.com/
Point the site checker to the script's URL: www.YourSite.com/yourscript.php
Set the monitoring interval to 1 hour.
Enjoy!

Automatized action on scheduled date in MySQL

I need an action to be realized automatically when a specific date is reached in a MySQL database, so not necessarly when a user is logged in the site and does an action.
This would go for many different entries in the table.
For example, when UTC_TIMESTAMP() reaches 'release_date' for different items, a PHP script would be executed, respectively for each items.
This is something I have never approached before.
I'm reading about Cron Job and MySQL EVENTS. Would that be the way to go?
Thanks in advance! Any help is greatly appreciated.
Lois
The best way to do this is to have a cron job that runs every time interval, you have full control of how often the script will run,
Within this script, you'll basically check the current time and see if it hits your 'release_date', then you run some queries against your db, if not, the script just exits.
so you can create a cron entry that runs every hour, like this
00 * * * * /usr/local/bin/php /path/to/script.php
and inside script.php
#!/usr/bin/php
$release_date = 1383135371;
$now = time();
if($now >= $release_date){
//Connect to database and do your code here
}
This way you'll have much more control of how things will work, this is not even scratching the surface of the powers of cron jobs !, let us know if things aren't clear :)
What you can do is create a PHP script that would run your query, do your comparisons, and then run the appropriate scripts. You would then run this script from the command line via cron. Here's a page that describes it in more detail
http://www.thegeekstuff.com/2011/07/php-cron-job/

Categories