3

So here is what I am trying to accomplish: User selects how often they want their post to be moved to the top of the page, whether it be every 30 minutes or every hour or every 2 hours, etc. They will be able to select how many times that it will do this. So if they select it to update every hour for 5 hours, it will then update the date/time in the database to the current time and then updates that time every hour for the next 5 hours and cancels it after the 5 hours are up.

I was thinking of running a PHP script like this to update the table since the ads are displayed by date DESC:

<?php
//cronjob.php
$id = $_SESSION['ad_id'];
$date = date('Y-m-d H:i:s');
$query = "UPDATE ads SET ad_date = :date WHERE ad_id = :id";
?>

Is there a best way to do that or will a CRON job that is selected by the user going to be too much load on the server to have users setting up CRON jobs continuously.

I saw this one approach and wonder if it is possible to set it up for this purpose. I am still getting familiar with CRON jobs.

How to start/stop a cronjob using PHP?

I will be setting this up on Godaddy's server:

Godaddy Cron jobs

Appreciate the help.

1 Answers1

3

One method is to store the required updates in a new database table, containing fields such as the post id, how many times to update, interval, how many updates are left, the time at which the first update should take place ( or the time for next update ) .

Then, create a php script that fetches data from this table and take necessary action for each post. Check if it's time to update the post, if yes then update, else don't ( check time with accuracy upto minutes, don't check seconds. If you can, do this time checking with SQL and not in php to reduce the data being fetched ). It's better to perform all updates in a single query to maximise efficiency.

Then set up a cron job on the server that runs this php script every minute or whatever minimum time interval you need.

This way, you can get away with just one cron job

If you need even more efficiency, then at the end of this script, check if there are any more updates pending, if none then delete the cron job. Then, set up your code such that whenever a user creates a new update, check if the cron job exists, if it doesn't then create it ( this additional dynamic cron job is only for efficiency freaks. If there are frequent update requests, it might be better to avoid creating/deleting cron jobs )

Arun A S
  • 5,531
  • 3
  • 25
  • 39