Using cron or something else? - php

I need to make an app where admin will add football match.
Then, these matches will show up on a home page and will be added before match is going to start of course.
Now, if he adds it in 17:15, and match starts in 20:45, I need it to have label match started and I will then disable it or remove it from page.
I'm using codeigniter php framework, I don't see they have something useful for cron jobs. Is using cron way to go in this case? I will probably need to use php native cron functions
Any advice appreciated

I don't see what cron could possibly do here, except maybe cleanup old database entries periodically.
All you need to do, is check the current time with the start time in your database.

cron is for server side where you need to perform sceduled tasks , cron displays nothing on front end of your application, you might need periodic calls to your script which then check whatever you want to check from database
jQuery(document).ready(function () {
setTimeout( function() {
// here you can call any javascript function which will access your script through ajax call
}, 1000 );

I don't think you need a cron job for this. PHP will evaluate code and construct your page every time a user requests it, so you can make sure that the appropriate matches for that exact time are displayed. You would just build your page around a query that selects matches where the ending time is later than the current time.

Related

Set database value after a certain date has passed

I have a database with variables I want to change depending on the date. The events in the database have dates. After this date I would like to set a variable 'past' to true. Meaning, the event has past. How can I approach this with php or is this something that needs to be added to the database itself (using phpMyAdmin) ?
Naturally, you first need code that does the actual update. This could very well be a PHP script, but you probably won't want to embed it into a web page, but to run it from the command line (see below).
Secondly, you need to execute that code on a regular basis so every update is done within a guaranteed time span after the event has passed. To execute scripts or other code regularly, you can use cron (if you are on Linux) and similar mechanisms.
If you need to make sure that the updates are done as fast as possible after the respective event has passed, you will need to write a full-blown daemon which runs in the background and does its checks 10 times per second, for example, or (instead of polling) uses appropriately programmed one-shot timers.
If you insist on writing the script in PHP and don't want to run it from the command line (as required by cron for example), you still can embed your code into a web page as usual and then use tools like wget or curl in conjunction with cron to retrieve that web page and get your code executed regularly.

Laravel - Trigger queue on form and update db after set time

I've been looking through Laravel's queue and schedulers and I'm not sure if it's what I need to do what I want. I'll try explain simply.
First, I hit a submit (basic form) that creates a db row with say a number and a created_at and finished_at. JS then creates a timer on the page that counts down (math) from the created at to the finished time.
I can do all that fine, what I'm struggling to get my head around is how do I make this then change that number value of 0 to 1 say after 10 minutes, or whatever time I wanted to specify? I'm not sure how to go about this. This sort of stuff is new to me.
Any help/pointing me in the right direction would be great! Explanations too. :)
Edit: To add, I looked at things like socket.io but I'm not sure if that's what I want too and if I can even use that with laravel as it's a framework off of node.js
Is the backend actually doing any work besides storage? If not I would skip the complexity of trying to open a web socket to tell the frontend the task is finished.
If all you're trying to accomplish is display something on the frontend to the user after an interval of time I would just use JS 100%.
However if the backend does need to do work and trigger the display change on the frontend you will need to open up a web socket.
Your constraint on Laravel's scheduling is that they are run at predefined times. So if these actions are triggered by the user and not a set time, skip using the scheduler. Instead use Events to broadcast something to node.

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?

Run function in "background"

Objects:
Object Sale
n Object User will participate on Object Sale
Each User can create one Object Agent
Each Agent will generate n Object Licitation (from time to time and with some conditions) for the object Sale
Goal:
Create a function that when a Sale has only 5 seconds left to end, will check all the Agents that there are for this Sale and post a licitation from the Agent that hasn't made a licitation on this sale the longest
This is something that needs to be continuously running since this agents would be in charge to replace users on posting licitations allowing them to be away during auctions.
My question
Updated (My question wasn't clear enough):
At index page of the sales I have a script with javascript that calculates the time left on a sale, so I can know when a sale should call the function to check for agents and place their bids, but my newbie question is: if I make a call for the function at this page, will this only work if the user has the page open? Or if he closes the function won't be called anymore? Because I need this to still work even the user closes webpage.
DaMacc already answered that this doesn't work
Updated (05/01/2010)
I've already created this function. The function will find all the sales that have 5 seconds left to end, then it will search all the agents and then place a bid from the agent that hasn't made a licitation on the selected sale the longest. Now i need this function to be called every second. I was going to use cron but cron has 1-minute boundaries. And I need this function to run on the server and not depend on the user that owns the agent.
Any suggestions?
PS: there are some auctions websites that have this kind of bidagents i'm trying to do, I could reffer one to use as example... But i'm not sure i'm allowed to do that here... :S
Thanks.
Create your normal function to do whatever it is you need to do and then use something like cron to set it up as a task to run every X amount of time.
Edit to expand on comments
In that case you are probably better off combining a few solutions. As mentioned in this question, I would recommend that you use cron to call a script every minute and in that script you run your process in a loop.
Some things to consider:
How long will each execution take?
Will you need to time_sleep_until at the end of each loop or will your script take longer than 1 second to run, in which case you will need to be calling the script multiple times from cron.
Be sure to keep track of how long your script has been running for as you don't want to have the situation where every minute you are taking up more and more resources as the script called the previous minute hasn't finished yet.
At the start of the script, take note of the current time, then at the start of each loop, check whether a minute has passed since the start of the script, if it has, exit the script (as another script will have taken over now thanks to cron).
Hope this helps. Let me know if this doesn't make a lot of sense and I'll try to clear it up a bit.
I wonder if this is what you are looking for:
function execInBackground($cmd) {
if (substr(php_uname(), 0, 7) == "Windows") {
pclose(popen("start /B ". $cmd, "r"));
} else {
exec($cmd . " > /dev/null &");
}
}
You can then start a php process in the background using the following method:
execInBackground("php path/to/file.php " . $param01 . " " . $param02);
// where $param01 and $param02 are optional values that you may want to
// send to the page. Equivalent to GET parameters of URL.
// You can include as many parameter values as you want.
//Example:
execInBackground("php automation/bidChecker.php daniel 53.25");
// automation/bidChecker.php is the file to be executed
// daniel can be the username
// 53.25 can be the bid value
And in the PHP file that runs in the background, you can access the parameter values using the following method:
$param01 = $argv[1]; // assigns daniel as value
$param02 = $argv[2]; // assigns 53.25 as value
This process can be started from within a script run when the user does something. It will also keep on running even if the user leaves the page and until you programatically break the operation.
I really don't know if this is what you are looking for. If so, you got it now.
Use a Queue, like Zend_Queue: http://framework.zend.com/manual/en/zend.queue.html . Just run an infinite loop (or two) and dispatch messages sent from your web application
Have you looked into using Javascript at all for this? If you have certain events that trigger the need to run this check, it may be the way to go.
You could write a js function included on every page that uses the the setInterval/clearInterval javascript functions to send an AJAX request to your server every few seconds and could send a different response back to the browser based on whether the conditions were met or not. (bandwidth may be an issue with this though)
I would recommend looking into jQuery and using it's AJAX functions for this.

PHP game update

Say I have a game in PHP which is a money making game and everyday the prices on items change on the market.
How would I make it so the prices in the database are automatically updated each day? Would I install a program on the server that detects when it has gone 24 hours then runs a PHP file which does the updating? Or os there another way?
Edit:
The thing is guys, I don't actually own the server I rent it from a hosting company so I don't really have access the the command line :s
Thanks, Stanni
Assuming you're on a Unix system, you should setup a daily cronjob. To do this, run "crontab -e" and enter something like:
9 21 * * * /path/to/your/script
This will run at 21:09 every day.
Since you probably don't have access to cron either what I would do is check how much time has passed everytime someone loads a page. If 24 hours have passed then call your update function. If 48 hours have passed then call it twice. If no one loads the page then it doesn't matter if the update function has been called or not because no one is looking ;)
Or you could setup a computer at home to call your update.php remotely every 24 hours. You can do that with a cron job and wget or if you're using windows you could use the task scheduler.
I think the first option will work the best. Call your update function every page load and only update when the 24 hour mark has passed. If you write it correctly it doesn't matter if it gets updated at the exact 24 hour mark.
If you don't have access to the commandline, you could add a 1x1 image to the website which calls a php script which checks if there needs something be updated.
something like
<img style="width: 1px; height: 1px; visibility: hidden" src="cron.php">
In cron.php you check if the data needs to be updated.
You want to set up a "cron job", or a PHP file that runs at a certain interval you set.
Check out this article for more information.
The best part about cron jobs is that you are not limited to the small subset of functionality available in say, stored procedures. You can use whatever logic you like! :)
Use webcron :)
http://www.webcron.org/index.php?lang=en
Or here is a good list:
http://www.onlinecronservices.com/
If you have a script that updates the prices and all you want to do is run it every day, use Cron (linux) or at command (windows).
How could you not 'have access to the command line'? I can't think of any host that doesn't allow ssh access. Having access to cron is a different story, but they SHOULD allow this, also. If they don't - find a new host!
Forget all that. There is no reason to do anything like that.
All you have to do is check each time someone calls the webpage. You keep track of the date and when the current date no longer matches your variable then you fire off the thing that gets new data. Bam! Of course that's not very scalable but it's fine for a small game.
I think that you can make a function that gets called every time a page is accessed, and verifies if the update took place, checking against a database.
So in a quick pseudo code:
function verify_often(){
if (last_update_in_db() != today() ){
update_db();
run_periodic_function();
}
return 0;
}
This method requires only the classic PHP & MySQL combination.
I couldn't work out how to reply to alex's answer but I wish to mention something that they said. When they said "check how much time has passed everytime someone loads a page" I feel that you don't need to check it every time the page is loaded. The better way of doing it would be to check when a user logs in. If it goes over 24 hours while users are still logged in it will not matter for the described scenario. The next time someone logs in the prices of items will change.

Categories