I work on a PHP project where users place advertising posts. When advertising post is placed online it is given a "hide date" (stored in database), when it will no longer be shown to the users. When "hide date" (e.g. next Monday at 10:00am) occurres I need to fire a script that makes changes in the database (not related to hiding the ad).
Question:
How do I run a script at the exact time in future(at "hide date").
I google'd a lot and didn't find any good solution.
Found possible solutions:
Cron isn't considered any more because of its lack of accuracy (for my task even seconds matter).
Write a daemon which will check every second if there is a record with a "hide date" but it can be very consuming.
Another way as I was told that message queues could be of help, but after reading some of the documentation I didn't find a way of setting date and time of processing the message in queue.
Can anyone point out where to look? Any tool/language is considered.
Let's suppose that ads show until a week after
Create a field in your ads table called expiry_date (timestamp)
When a new ad is inserted, do the following
$expiry_date = strtotime("+ 7 days");
Then insert the expiry date along with the record
Next, in the page that displays the ads, select only ads whose expiry date did not pass yet, so
SELECT * FROM ads WHERE expiry_date >= NOW()
This will only show ads that didn't expire yet.
If your site is running on a linux server, you can add a cron job to trigger your update script.
If your site is running Windows, use Task Scheduler instead.
However, it doesn't really sound like your best solution. You could store the "hide date" in the database along with the rest of the post's data. Then you can simply filter the posts in your display code.
Related
I'm create a small browser game and I'm programming the resource handler.
I'm using PHP and MySQL database.
I realised that I can't update the database every second to increase my resources, so reading on Stackoverflow, I found this post:
I am also trying to make a online game in PHP and encounter also this
problem. My solution was actualy pretty simple. In Assuming you are
using different city's or planets, you will need a database table for
the city/planet. In this database you store the current resources and
the resources per hour. And also a timestamp.
For upgrading resources facility (gold mine for example) i have a
database that has all the building ques with a begin time and end
time.
i then have made a page that i include on every page in the game. It
first checks if there
are any building ques for the selected city that
should be finished since last time database was entered. If that gold
mine was finished at let say 12.00 and the timestamp on your city was
11.00 and current time is 13.00. What the page does, it calculates all the resources for the time 11.00 to 12.00. Then it will update the
gold per hour in the city table. And then it recalculates the
resources from 12.00 to 13.00.
when all the above is done, it puts the timestamp on current. But as
you have all the resources per hour from the second run, you can store
it in an array and let a local timer run to update the resources on
screen. But since you include the above mentioned page on every page,
when you go to the next page it will acces the database to see what
the current resources should be. So the local data is only for
viewing.
By DutchEcho
This is the link: LINK
I programmed the events queue and everything is fine. The problem, now, is to increase the resource if the player is online.
If I save the last_login of the player by time() and then I calculate the new amount of production I have a problem:
"UPDATE `stats` SET `rock` = `rock`+(('".time()."' - $last_login)*$rock_production)
I do: time() - $last_login. If I save the last_login every time a player reloads or changes page, this difference will be always 0.
Because the two times are equal.
How can I increase my resource every second?
Rather than updating last_login on each page load, only update when you start a session. You might have a second field that you update on each page load, and use the difference for your calculation. The two fields could also be used to indicate the duration of the most recent "time on line" even after the user disconnects.
[edit]:
How about using an update trigger? In a single statement you would have both values of last_login available - the new value and the original value.
I am trying to build an online attendance system where employees sign in and check in daily except for weekends and vacations.
so , my idea was to create a daily attendance record as a table in the database.
Attendance_date_daily date
Employee_ID number(auto generated)
Check_in_time time
Check_out_time time
Attendence_status varchar
I am using codeigniter v 3.0.0
it's easy to create a model to get the current time and save it in the database when the user check in/out.
but the problem is that, if the user was absent for a day or more , then the system will not create a record for those days.
moreover, i can't create the records beforehand. since i don't know when the user will have his/her vacation and working days may differ.
what is the best way to create and manage those daily records?
One possible solution may be to allow the employees to do their check-in each day normally which would populate the database for those days.
In order to add the absence records for those who have not checked in you could use CRON or something similar to schedule a task at perhaps midnight each day. Use this task to target a url that would run a method in a controller that will check employees against the daily records. Obviously for those whom have checked in no action will be performed, although for those who have not and are not marked as on vacation or not working you update the database to add the absence records.
With a system like this you would typically invoke the url to perform the update using whatever system you use with wget or something similar to 'load' the url and force it to run. A security consideration also would be that you'll want to add in a secret key as a GET parameter or something similar so that the method can check that it's being invoked via the task and not e.g. someone visiting the url by comparing the GET parameter with a stored key that you've set.
I'll try to explain my question the best way I can.
I'm not asking for codes, only for the best method of doing it.
I want to create a browser game and use time for upgrading stuff, building etc.
For example, to build 1 house will take 1 hour.
So I will began with saving the timestamp+(60*60) at the moment the user did his action.
My question is, how to update it the best way?
One way I thought of was to add function that check every page view of the user if it's done.
But then if he's not logged in the update wont happen.
Second way i thought about is for every page view of any user to check for every user registered. But it's not effective and there is a problem if no user is logged in.
Any suggestions?
I had my game doing it simply, without crons.
When a player wanted something that takes time, i just updated his database information with the appropriate time of ending that job (columns are just examples)
UPDATE player SET jobend = UNIX_TIMESTAMP() + (60*60*4) # ending in 4 hours
Then, every page that had an information about the remaining time, i just used something like this:
SELECT (jobend - UNIX_TIMESTAMP()) AS jobremaining FROM player
I formatted correctly the time using strftime and i displayed that to the user.
In the case the remaining time was negative, the job was done.
There was no-need for absolute counting since user was able to do something with the job when he was connected.
When the player just changed pages or doing something else i had a function where i just checked all timely events while the user was online (so to catch any negative timer), then presented with javascript any change (i posted javascript counters for every page)
Now, if you talk about updating in real-time, cron is the way but are you sure you're going to need it for a game? I asked that question myself too and the answer was not.
EDIT
If another player sees the buildings on schedule page (an hypothetical page) i am doing the same calculations; if a time just got negative for a specific player (regardless if another player see the page), i just reward him with the building (in database i make all the changes), even if he's offline. There's no harm in this, since he can't do anything anyway. The other players will just see he has a building. The key here is that i execute the required updating PHP code regardless of player's connection to the game; as long at least ONE player is logged-in i'm executing the progress function for everything.
This isn't so slow as it sounds (updating all players by using just a connected player that visits a specific page). You just have a table of 'jobs' and check timers against the current time. More like a single query of getting the negative ones.
I know the title is complicated, but i was looking for some advise on this and found nothing.
Just want to ask if i'm thinking the right way.
I need to make a top facebook shared page with about 10 items or so for my website items (images, articles etc.)
And this is simple, i will just get the share count from facebook graph api and update in database, i don't want to make it in some ajax call based on fb share, it could be misused.
Every item has datetime of last update, create date and likes fields in database.
I will also need to make top shared url in 24h, 7 days and month so the idea is simple:
User views an item, every 10 minutes the shared count is obtained from fb graph api for this url and updated in database, database also stores last update time.
Every time user is viewing the item, the site checks last update datetime, if it is more than 10 minutes it makes fb api call and updates. It is every 10 minutes to lower fb api calls.
This basically works, but there is a problem - concurrency.
When the item is selected then in php i check if last update was 10 minutes ago or more, and only then i make a call to fb api and then update the share count (if bigger than current) and rest of data, because a remote call is costly and to lower fb api usage.
So, till users view items, they are updated, but the update is depending on select and i can't make it in one SQL statement because of time check and the remote call, so one user can enter and then another, both after 10 minutes and then there is a chance it will call fb api many times, and update many times, the more users, the more calls and updates and THIS IS NOT GOOD.
Any advise how to fix this? I'm doing it right? Maybe there is a better way?
You can either decouple the api check from user interaction completely and have a separate scheduled process collect the facebook data every 10 minutes, regardless of users
Or, if you'd rather pursue this event-driven model, then you need to look at using a 'mutex'. Basically, set a flag somewhere (in a file, or a database, etc) which indicates that a checking process is currently running, and not to run another one.
I'm writing a website where users can order products, but the catch is that the products should automatically checkout (executes PHP script including MySQL queries) after 5 minutes even if the users logout/close the browser, etc. Has anyone had a problem similar to this. How should I go about coding this?
Since this is a recurring automated task, you will need to set up a cron or other task scheduler. Crudely, this is how it would work:
When user adds product to shopping cart, it goes into database with a flag indicating that its not checked out along with timestamp of addition to db/shopping cart.
If the product is checkout by the user explicitly from the browser, this flag is updated to reflect the same.
The cron wakes up every one or two mins and checks this table for timestamps of items added to shopping cart without checkout flag updated and added more than 5 mins before.
It checks out such products and updates flag.
Please note that you will still need to further tweak this flow to handle situations like what happens if the user is manually checking out while your cron is doing the same etc etc
But on a nutshell I think this is how I would proceed to tackle the issue
Store the info related to products to be checked out in database.
A cron job running every minute will cause checkout for products 5 min old.
Here is what I would do. MySQL as far as I know cannot have a timed delay. You can have a cron job that runs and executes statements. What I would do is make an extra field in the shopping cart table and set a future checkout time. Make a cron job that runs every minute on the server. Have that cron job just do a quick poll of shopping carts with checkout times less than the current time. If it finds one, run the checkout procedure on that cart and either delete it or mark it as checked-out so that it doesn't re-check it out again.
While I can't provide you with sample code as you haven't provided anything, this will at least give you a jumping off point.
Surely a person wants a similar experience to visiting a store?
Like picking up things and wandering around.
Perhaps that person has decided to leave the basket at the counter? By all means have a product on offer for a time period and inform them that the time is up (or needs to be bought withing X minutes)
So why the auto checkout stuff?
One assumes that you do not want a bad reputation over a person deciding not to buy something and you are taking the cash? Perhaps that persons internet connection has died/laptop ran out of power/...?
Just please let them have to go through a checkout and it will paid better dividends than being automatic sold stuff they might not want....
I really think that 5 minutes is to small duration for this kind of verification, but you should have a cron job which runs a php script every 5-10 minutes which verify the last date of users activities and the last (unfinished) orders. If date is smallest then actual date time() minus 5 minutes, then you should delete the entries of that user from db.
The verification should be made from orders table, and not for every existing user.
If the user is leaving the page, I suppose he requested the page (it was not automatically executed, like a cronjob).
The normal behaviour of php is to execute the script completelly, even when the usr leaves during this.
Just an idle though - Is this shopping experience is for one off products (like antiques) or run of the mill things (like groceries)?
If the latter rather than the former, why bother? Surely a good store could replenish and therefore sell that particular product at a given price regardless. If the former an auction is required.