Run PHP script every 5 minutes for 2 hours upon command - php

The "upon command" part of the title is essential. I know how to set a cron job to run a PHP file at a pre-determined time schedule. What I need is similar in nature, but I think it requires a different technical solution.
I have an admin section, and when one of my admins logs in, they should be able to click a button which gets a PHP script to execute every 5 minutes for the next 2 hours.
Right now the button exists, and it calls a Javascript function which sends an AJAX request to the appropriate PHP file. It would make our lives a lot easier if the PHP function in the file could be told to run every 5 minutes from that moment until 2 hours have passed.
I'm aware that something similar could be done client-side by having Javascript repeat the request every 5 minutes. However, that doesn't help me a lot. An admin needs to be able to leave the site, send new requests to the same file with different parameters, all the while not interrupting the repeated execution of the PHP script.
So, I need some sort of server-side solution for this. Is that even possible? If so, what do I do?
I can share the client-side code but I don't think it really matters - the client side is a standard AJAX call; on the server side it's just this:
$par=$_GET['par']; //parameter received from AJAX
someFunction($par); //I need to modify the code so this function (please note there's a parameter) would run every 5 minutes for the next 2 hours

A javascript solution would require that the admin would need to click the button then leave that page open for the next 2 hours which is far from ideal. I assume this is why you don't want this.
This is one method
When your admin clicks the button store the date and time in a database or file
Have a cron job run every 5 minutes regardless
The first thing the cron job does is check whether that stored datetime >= now - 2 hours
If it is not, 2 hours have passed since admin last pressed the button, die()
If another admin clicks the button just overwrite that datetime for that job with the new value. The job will then always run every 5 minutes for 2 hours since the last click.

Use the at shell command inside your php so it can call itself. Then use php to manage how many times its called or set them all up in one go

Related

Why does a cron link respond with a delay when it works more than once?

There is a php function that does some database and curl operations. I run this function with a url. Right now I'm doing this manually, but I'll tie it to crons in the future.
My problem is this. For example, I have a url like below.
domain.com/crons/update_account_data?token=xxx
When I enter to this url, the function I direct inside deletes data from the database and processes data from a different service.
I ran the url 3 times at the same time. It immediately deleted the data from the database on the first run. But the second run started after a certain time (for example, after 10 seconds), and the third start after a certain time (for example, after 20 seconds).
What is the reason of this? I want these 3 links that I run at the same time to start operations at the same time.
I solved the problem. There is no problem when I enter 4 urls as follows. But I still don't understand why it works delayed if they are all the same.
domain.com/crons/update_account_data?token=xxx
domain.com/crons/update_account_data_2?token=xxx
domain.com/crons/update_account_data_3?token=xxx
domain.com/crons/update_account_data_4?token=xxx

Executing function to alter database every 15 minutes

I am currently working on a project that runs online tournaments. Normally admins of the site will generate brackets when it is time for the tournaments to start, but we have run into inconsistent start times, etc. and i am looking into proper ways to automate this process.
I have looked into running cronjobs every x min to check if a bracket needs to be generated but i am worried about issue when it comes to overlapping cronjobs, having to create/manage cronjobs through cpanel etc.
I was thinking about other solutions and thought it would be great if a user could load a page, the backend checks timestamps and determines if the bracket should be generated. An event is then fired/set to begin the auto-generation process elsewhere so it does not impact user load times. I just do not know the best route of going about this.
PS: I just need an idea of the direction i should be looking into so i can learn how to solve this issue i am not looking to copy and paste code. I just haven't been able to find anything. All of my search results provide cronjob examples.
EDIT
After thinking about things could using this work?
$(document).ready(function() {
$.ajax('Full Url Path Here');
})
I don't need to pass user input, or return any data i simply need a way to fire an event, it would be easy to include this only when needed via a helper class. Also i won't necessarily have to worry about users attempting to access i can restrict the route to ajax only requests and since nothing is needed/used on input or returned as output what can happen?
You could do it everytime a user loads a page (idea not tested, but theoretically possible):
1) Create a file and store the timestamp of the last time you updated the database.
2) Everytime a user loads a page, read that timestamp and check if 15 minutes passed.
3) If 15 minutes passed: Run a background script (with shell_exec?) that will do what you want and update the timestamp when it's done executing.
One obvious flaw with this system is that if you have no visitors in let's say a 30 minute frame, you will miss 2 updates. Though I guess that if you have no visitors you also have no point in generating brackets?

Timer mysql php check

It's bugging me for a day now and I really cant find out, I have a basic login/register page, and when registering, a timestamp is stored in the mysql database(table timer, column cooldown):
$settime = mysql_query("INSERT INTO `timer` (`cooldown`) VALUES(0)") or die(mysql_error());
What I want to do now (I'm creating a browser mmorpg), Is when I do a specific POST request, I want a timer in my database to go off. This timer should be 1 minute, and also be shown for users, like: <?php echo $timer['cooldown']; ?> Whenever the timer is = 0, I can do a specific function again, and the timer will be set to 60 seconds again.
Sorry for the lack of knowledge but I can't find out anywhere how to do this.
What you're trying to do here - a background job - goes against the web development principle of a request-response cycle in the shared-nothing environment of PHP.
But there are several ways to break up the rigid cycle:
If you just need to do some DB updates after 1 minute, you can use MySQL events: http://dev.mysql.com/doc/refman/5.1/en/events.html
If the function you want to call is not running too long, you can check on every user request if there are entries in the timer table that are older than 1 minute.
Create a PHP script that is called by a cron job every minute. It checks if there are unhandled items in the timer table and does something with them.
Create a PHP daemon script that wakes up every minute to check.
If you need to change something on the user page after 1 minute, doing the PHP script call client-side with a JavaScript timeout and AJAX or websockets is the better option.
For displaying the countdown to the user, you have to use JavaScript. If you are using the server-side timer, you can use it just for display purposes, hiding the countdown when it's finished. To work around the "user opens new page before timout is finished" problem, put the data for the remaining seconds in an HTML data attribute where your JavaScript code can read it.

How to launch a php script 12 hours after each user triggered event

Any of the users can trigger an event, as many times they wish. Each time this event is triggered, a row in a mysql table is created with the timestamp, their userid and other useful information. What I need to do is launch a script which runs exactly 12 hours after the event is triggered i.e. for each row in the table.
How can I achieve this in an automated and efficient fashion?
You could use a cron job which every minute launches the script.
In the script you should first fetch the row(s) and check if it's OK to run (if 12 hours passed) then continue, else stop.
I don't know if this will be very efficient, it depends on your number of entries in the database, but technically it's not expensive to just check if the current date matches a date fetched from the database + 12 hrs, I cannot say more because you didn't give too much details about your data.
You'd probably be better off with a cronjob
http://en.wikipedia.org/wiki/Cron
Potentially, you could look into MySQL event scheduler. Although It might not fit your needs, hard to really tell on the details given
http://dev.mysql.com/doc/refman/5.1/en/events.html
something like
CREATE EVENT myTimedEvent ON SCHEDULE EVERY INTERVAL 5 minutes DO CALL updateRows();
updateRows checks your criteria (12hours ago), if it is, perform whatever action you want to do. This requires your MySQL to be # version 5.1+ however
You would probably best have a cron job which runs every minute and checks for any rows in the database > 12 hours old that have not yet been processed the script and process them. This wont give you EXACTLY a 12 hour difference, but would give you a difference within a minute of that.
You would probably also want to make sure that script would be able to run within a few seconds such that you don't have overlap of the script running twice at the same time.
This could be done using CronJobs. If you have root access to your Server or a server administration toolkit that offers cronjob managment you would do it on your server. otherwise use an online cronjob service (google for cronjob online).
the cronjob then triggers a php script on your server in your defined interval, like every minute or every 5 minutes.
this script then selects all rows from your mysql table which are older then 12 hours (WHERE timestamp <= NOW() - INTERVAL 12 hour ) and performs your desired actions on each result and delete the result from the table (or mark it done),
just make sure that the fetching and the actions itself are faster than your cronjob interval, otherwise you would have two or more scripts working on the same rows.
The easy way for me is to make the page head contains
<head>
<meta http-equiv="refresh" content="43200"> <!-- 43200 for (12 hours × 60 mintes × 60 seconds) -->
</head>
This method is very helpful to avoid server time out, which you can't avoid if you are using only PHP code
Important if you start the script using submit button, it's recommended to make the form action="other_page" not the same page, and sure you should save your input values as cookie using setcookie function and grab it as a variable in the action page using $cookieVar = $_COOKIE['the_cookie_name'] ;
You may need to increase or decrease the $cookieVar value and update the value again using setcookie every time your head code http-equiv do the refresh automatically after the specific seconds (43200 in our example) depends on what you want to do
Note that if you make your action start automatically without pressing submit button you can do the action in the same page.
I did that idea before, I had 180,000 images in one folder and the server didn't allow me to download it all because it was showing me only first 7998 images, so I create a script to zip each 1000 image in a file outside the images folder and to avoid time out, I made the code refresh each 60 second , finally I got only 180 zip file :)

i have a problem with my php ajax chat script

hello i have some problems with my php ajax script
i'm using PHP/mysql
i have a field in my accounts table that will save the time for the last request from a user, i will use that to kick the idle user out of the chat. and i will make a php function that will delete all the rows that its time field more than the time limit, but where should i use this method is it okay to fire it every time a new request sent to my index.php ? i think that will make a huge load on the server,is n't it ? do you have a better solution?
thanks
There are two viable solutions:
either create a small PHP script that makes this deletion in an infinite loop (and of course sleeps for a specified amount of time before doing it again), and then start it via PHP CLI,
or create one that makes the deletion only once, then exits, and call it from cron (if you're using a UNIXish server) or Task Scheduler (on Windows).
The second one is simpler, but its drawback is that you can't make the interval between the deletions shorter than 60 seconds.
A solution could be to fire the deletion function just once every few requests.
Using rand() you could give it a 1 in 100 (for example) change of running the function, so that about one page request in a 100 will clean up the expired data.

Categories