Safe Crons

Post all your tuts or request for tuts here.
Post Reply
User avatar
MikeD
Posts: 294
Joined: Thu Sep 08, 2011 4:28 am

Safe Crons

Post by MikeD »

Sorry if this has been posted somewhere already. This idea hit me when coding the Market which uses time functions.

As far as I can tell, it's pretty much fool proof, down to basically the minute.

First, create a new table in the database, I named my `crons`. It will need 2 columns, `cronname`(varchar) and `lasttimeran`(int)

Insert names for your crons, I called mine Dungeons which resets the characters dungeons every 24 hours.

Sorry if this doesn't work 100% right, I am very tired :P

Now for the script.

Code: Select all

<?php
include 'connect.php';

function secondsToWords($seconds,$db)  //This function finds how much time has passed.
        { 
        /*** number of days ***/ 
                $days=(int)($seconds/86400); 
        /*** if more than one day ***/ 
        $plural = $days > 1 ? 'Days' : 'Day'; 
        /*** number of hours ***/ 
                $hours = (int)(($seconds-($days*86400))/3600); 
        /*** number of mins ***/ 
        $mins = (int)(($seconds-$days*86400-$hours*3600)/60); 
        /*** number of seconds ***/ 
        $secs = (int)($seconds - ($days*86400)-($hours*3600)-($mins*60)); 
        /*** return the string ***/ 
        if ($days == '1' OR $hours =='23' AND $mins == '59') //It's been 24 Hours or 23 hours 59 mins since the last script ran. You can easily change this to what you need specifically.
        {
        $time=time();
        $query = "UPDATE `characters` SET `dungeons`=`dungeons`+`maxdun`, `battles`=`battles`+`maxbat`;";
        $query .= "DELETE FROM `armory` WHERE `itemname`=`itemname`;";
        $query .= "UPDATE `crons` SET `last`='$time' WHERE `cron`='Dungeons'";

        mysqli_multi_query ($db, $query) or die("MySQL Error: " . mysqli_error($db));
        mysqli_next_result($db);
        mysqli_next_result($db);

        echo "script ran successfully"; //I echo it out for the emails I receive to make sure the script has run.
        }  
        elseif ($days != '1' OR $hours != '23' AND $mins !='59') //Too little time has passed since it last ran.
        {
          echo "You are not authorized to execute this script!";
          exit;
        }
        }

//Get info from the `crons` table.

$timecheck="SELECT * FROM `crons` WHERE `cron`='Dungeons'";
$timecheck2=mysqli_query($db,$timecheck) or die (mysqli_error($db));
$timecheck3=mysqli_fetch_array($timecheck2);

$time=$timecheck3['last'];

$seconds=(time() - $time); //This finds the total seconds from the start of this script and the last time it ran to enter into the function.


secondsToWords($seconds,$db); //Call the function...

?>
Post Reply

Return to “Tutorials”