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.
Related
Hello guys I need an advice with these situation :
For example I have a free classified posting website where in a user can post classified ads..
The ad would be listed on the website for a maximum of 30 days then on 31st day it will automatically be deleted on the database as well as the images on the server.. The question is :
$db_ad_tbl('id','user_id','title','description',timestamp);
What is the right approach for doing this?
Can anyone suggest tutorials/links that covers this the same situation?
Another approach that does not require cron is to use MySQL events. If you can come up with the correct query, you can set it as a recurring event. phpMyAdmin 4.0.x supports events handling from the interface.
See http://dev.mysql.com/doc/refman/5.5/en/events.html.
As Barmar has noted you should add a cronjob for this task. You can write a simple php script and then add it to your crontab with something like:
1 0 * * * php -f /path/to/file/clean.php
This means that the php file will be executed every day at midnight.
Just a few notes:
the file should not be in your web folder
you might want to do some tests and report errors by email(such as unable to connect to db)
If you build more of thees you should keep a list of them somewhere in case you switch servers(or the server dies)
if you use a config file(ex:to store your db connection details), you should make sure that it is accessible by the user that the cronjob works with.
Most hosting platforms allow for crontab editing and run them with the same user they run the web server so it should not be a problem.
There is really no other good solution to this then creating cron job. This is of course if you don't check the time stamp every time you get the data from the database.You can then delete it if it is bigger then the expiry data (DELETE FROM my_table WHERE timestamp>[Expiry Timestamp] ). This is of course risky, since you will have to include the timestamp every time you try a count, and risk storing everything forever if no expired resource is ever requested from the database.
I have a php function live on my webpage. It runs whenever someone reloads that page and probably when google etc. crawls it. I only want the major part of it to execute once every hour though.
I was thinking about storing a timestamp in a database and only execute it if 59 minutes has passed since it ran last. Is there a better/simpler way? Could it for instance be stored in some global lasting php variable or such?
It seems a bit overkill to create a table and only keep one timestamp in it. I don't have access to the local machine the code is stored on.
Thanks for any suggestion!
As AmazingDreams said, using a cron job is probably the best approach for this, especially seeing as it looks as if you're wanting to run this script once every hour. If you're using Windows, you can use the Windows Task Scheduler instead.
I am trying to create a site in PHP and MySQL where a person is assigned to do a task for another person. Time period allotted to complete the task is 72 hours.
If done, the other person will confirm so. If not, I want to take certain actions (like blocking his account, sending an email, assign the task to someone else etc.) What is the best way to do this?
As the count-down runs second-by-second, I guess I will have to run a script every second.
You could use a cronjob to check for the deadline and eventually send the email, block the account, etc...
Although, if you actually need a persecond precision, you might want to use a single process with an "infinite" cicle and some sleeps in between.
If your server is from *nix family, you could use cron/crontab. See examples of usage at: http://en.wikipedia.org/wiki/Cron and https://help.ubuntu.com/community/CronHowto
Very few things have to happen truely immediately. If you've waited 72 hours for something to happen, having an action occur within a matter of a few minutes will not matter so much.
If you really do want something to happen so quickly, and you will always have a long time between potential events, one thing I would suggest is not using a cronjob, but something more akin to what #muc has suggested - a script that runs regularly within a shell script that will keep it going (just doing an 'exec $0' at the end to rerun the script when it would exit).
The script (in PHP for example) that checks the database doesn't have to be running all the time either. Whenever it finds something that is due to happen in more than a few seconds time, it sleeps till the next event is due to happen. When it wakes up, it can double-check that it is still required, and then performs the relevant job.
<?php
$jobId = whatToRunNext();
if (! $jobId) {
exit;
}
$secsToNextJob = howLongToNextJob($jobId);
if ($secsToNextJob > 0) {
sleep($secsToNextJob);
if (! jobStillRequired($jobId)) {
exit;
}
}
doJob($jobId);
exit;
Wrap that in a shell sript that will keep it running, maybe with a small sleep in the bash script, and you'd be good - while not being in a very long-running, cpu-killing loop.
If I needed to do something like that, I would probably go by these steps:
Create event and calculate deadline
Set up a cronjob to run at the deadline time
cronjob checks the event status and takes actions
I think this will be the most efficient way in doing it.
I am trying to create a site in PHP and MySQL where a person is
assigned to do a task for another person. Time period allotted to
complete the task is 72 hours.
These could simply just be db vales
table_task
.id
.user_assigned
.strart_date
.end_date
.status
.desc
If done, the other person will confirm so. If not, I want to take
certain actions (like blocking his account, sending an email, assign
the task to someone else etc.) What is the best way to do this?
This again, Admin panel of some form with a layout of assigned jobs, the ''worker'' should be required to post a job as ''done'', the ''admin'' can then confirm this. This can all be managed via Values in the db ''table_task.status''
As the count-down runs second-by-second, I guess I will have to run a
script every second.
^-- server suicide
Run the cron ever hour at most. If you have 1000 users. Then this cron will run 1000 a sec
in an hour this is, 60000*60
If you need to display the time use some jQuery of some form. There are lots of clock scripts.
I am trying to create a PHP code that will execute once every 24 hours. The current CMS that I am using supports this, and it works correctly, whereas, I want to make it a little more complicated.
For one hour, every day, I want a code to execute, which will give special permissions to my users during this one hour.
Once the hour is up, I would like it to revert the changes, taking away the permissions. The users would then need to wait until the next day, when the hour is back.
For example:
<?php
if (!defined('UBER') || !UBER)
{
exit;
}
dbquery("UPDATE catalog_pages SET visible = '1' WHERE id='91'");
$core->Mus('update_catalogue');
?>
This code executes once every 24 hours, and works fine. It updates the catalogue setting a page to be visible to everyone. I am only stuck on how to make it disappear after the hour is up.
Lets say that the hour is 4.00am to 5.00am.
How would I make the page disappear after 5.00am using a PHP code?
Thanks in advance.
if (date("G") == '4'){
//give
}elseif (date("G") == '5'){
//takeway
}
or in the query
.. WHERE HOUR(NOW()) BETWEEN 4 AND 5
This is actually really easy to do. When the user logs on or tries to use a permission that is only granted at the certain time, run a check to see if the time is within those hours. If your CMS allows you to intercept events, use something like this:
onUserAction(){
if(isSpecialHour()){
denyPermission()...
}
else{
grantPermission()...
}
}
When the user tries to do something that requires a permission, the system should check if it is within that special hour period and then either grant or deny permission.
With PHP alone, it is impossible to have a script run at a specific interval. PHP scripts are run when they are loaded, and unless you have someone run the scrip at that exact time (or use something like cron) it can not be done. Of course, you could use cron or simmilar to accomplish the same thing. The above method is probably your best bet though.
How can I set up a program in which a certain piece of data for a user is updated every hour. One example I can give is Mafia Wars. When you obtain property, your money is incremented every set amount of time based on which property it is. I'm not asking to spit out code for me, but rather to guide me in the right direction for a solution. I tried looking into cron jobs, but that only runs a script on a set time. Different users are going to be using this, and they may have different times to update their information. So thus, cron jobs are not applicable here.
You could still have cron jobs, just lots of them (not one per user, but maybe one per minute).
Also, Mafia Wars strikes me as not very interactive, so it may be enough to just update the data (after the fact) when the user (or some other part of the system) next looks at it. So when you log in after 37 hours, you get all the updates for the last 37 hours retroactively applied. Cheap trick, but if there is no need for a consistent global view, that might work, too.
A solution that I came up with when wondering how to implement such a thing is that whenever the player saves the game, the game saves the current time. Then, when the player loads the game back up, it calculates how many minutes have passed and figures out how much money the game should give the player. Then, you could update the SQL database to reflect the changes.
Why do you dismiss cron jobs? Have a cron job that runs a script in short intervals. Within this script, include logic to check which specific updates on the database have to be done.
A cron job that runs something is your friend.
What that something is, is up to you. It could be a PHP script that runs some mysql queries or procedures, or it could straight mysql command from the command line.
Either way, Cron (and other similiar tools) are exactly the bill for these tasks. It's lightweight, on nearly every server in the land, lots of help avaliable for it, and it 99.9999% of the time, it just works!