Jump to content
MakeWebGames

Need to replace my cron_minute with a timestamp


Recommended Posts

Magictallguy made this one quite a few years ago but has served me well since.

create file called cronless_crons.php and stick this in it.

<?php

if ('/cronless_crons.php' == $_SERVER['PHP_SELF']) {
    exit;
}
if (!isset($set)) {
    $set = array();
    $settq = $db->query('SELECT * FROM settings');
    while ($r = $db->fetch_row($settq)) {
        $set[$r['conf_name']] = $r['conf_value'];
    }
}

// Minute
$result2 = $db->query("SELECT * FROM updates WHERE name = '1min'");
$result1 = $db->fetch_row($result2);
$hla1 = time() - $result1['last'];
if ($hla1 > 60) {
    $n1 = floor($hla1 / 60);
    $db->query(sprintf('UPDATE `users` SET `hospital` = GREATEST(0, `hospital` - %u) WHERE `hospital` > 0', $n1));
    $db->query(sprintf('UPDATE `users` SET `jail` = GREATEST(0, `jail` - %u) WHERE `jail` > 0', $n1));
    
    // minute Cron stuff here
    
    $hc = $db->fetch_single($db->query('SELECT COUNT(`userid`) FROM `users` WHERE `hospital` > 0'));
    $jc = $db->fetch_single($db->query('SELECT COUNT(`userid`) FROM `users` WHERE `jail` > 0'));
    $db->query("UPDATE `settings` SET `conf_value` = '$hc' WHERE `conf_name` = 'hospital_count'");
    $db->query("UPDATE `settings` SET `conf_value` = '$jc' WHERE `conf_name` = 'jail_count'");
    $time = time();
    $db->query('UPDATE `updates` SET `last` = '.$time." WHERE `name` = '1min'");
    $floor = $time - (floor($time / 60) * 60);
    if ($floor > 0) {
        $newUpdate = time() - $floor;
        $db->query('UPDATE `updates` SET `last` = '.$newUpdate." WHERE `name` = '1min'");
    }
}

// Five minute
$result2 = $db->query("SELECT * FROM `updates` WHERE `name` = '5min'");
$result2 = $db->fetch_row($result2);
$hla2 = time() - $result2['last'];
if ($hla2 > 300) {
    $n = floor($hla2 / 300);


	$db->query('UPDATE `users` SET `brave` = LEAST(`brave` + (((`maxbrave` / 10) + 0.5) * '.$n.'), `maxbrave`), `hp` = LEAST(`hp` + ((`maxhp` / 12) * '.$n.'), `maxhp`), `energy` = IF(`donatordays`, LEAST(`energy` + ((`maxenergy` / 5) * '.$n.'), `maxenergy`), LEAST(`energy` + ((`maxenergy` / 10) * '.$n.'), `maxenergy`)), `will` = LEAST(`maxwill`, `will` + '.($n * 100).')');
    $db->query('UPDATE `pets` SET `energy` = LEAST((`energy` + ((`maxenergy` / 30) + 2) * '.$n.'), maxenergy) WHERE (`energy` < `maxenergy`)');
    $db->query('UPDATE `pets` SET `hp` = LEAST((`hp` + ((`maxhp` / 30) + 2) * '.$n.'), maxhp) WHERE (`hp` < `maxenergy`)');
	
    // 5 minute cron stuff here

    $floor = $time - (floor($time / 300) * 300);
    if ($floor > 0) {
        $newUpdate = time() - $floor;
        $db->query('UPDATE `updates` SET `last` = '.$newUpdate." WHERE `name` = '5min'");
    }
}

// 1 hour
$result3 = $db->query("SELECT * FROM `updates` WHERE `name` = '1hour'");
$result3 = $db->fetch_row($result3);
$hla3 = time() - $result3['last'];
if ($hla3 > 3600) {
    $n3 = floor($hla3 / 3600);
    
	
	
    // Hourly cron stuff here
    
    
    if (17 == date('G')) {
        // 5pm crons here like workpayouts
    }
    
    
    if (8 == date('G')) {
        // 8am crons here
    }
    
    
    
    if (60 == $set['validate_period'] && $set['validate_on']) {
        $db->query('UPDATE users SET verified=0');
    }
    $time = time();
    $db->query('UPDATE `updates` SET `last` = '.$time." WHERE `name` = '1hour'");
    $floor = $time - (floor($time / 3600) * 3600);
    if ($floor > 0) {
        $newUpdate = time() - $floor;
        $db->query('UPDATE `updates` SET `last` = '.$newUpdate." WHERE `name` = '1hour'");
    }
}








// 1 day
$result4 = $db->query("SELECT * FROM `updates` WHERE `name` = '1day'");
$result4 = $db->fetch_row($result4);
$hla4 = time() - $result4['last'];
if ($hla4 > 86400) {
    $n4 = floor($hla4 / 86400);
    $db->query('UPDATE `fedjail` SET `fed_days` = GREATEST(0, `fed_days` - '.$n4.')');
    $q = $db->query('SELECT * FROM `fedjail` WHERE `fed_days` = 0');
    $ids = array();

	
	
	// Daily cron stuff here
    
    if (1 == date('j')) {

            // First of the month Crons here
        }

    $time = time();
    $db->query('UPDATE `updates` SET `last` = '.$time." WHERE `name` = '1day'");
    $floor = $time - (floor($time / 86400) * 86400);
    if ($floor > 0) {
        $newUpdate = time() - $floor;
        $db->query('UPDATE `updates` SET `last` = '.$newUpdate." WHERE `name` = '1day'");
    }
}





// 1 Week
$result5 = $db->query("SELECT * FROM `updates` WHERE `name` = '1week'");
$result5 = $db->fetch_row($result5);
$hla5 = time() - $result5['last'];
if ($hla5 > 604800) {
    $n5 = floor($hla5 / 604800);

    // Weekly Stuff Here if you have any
        

    $time = time();
    $db->query('UPDATE `updates` SET `last` = '.$time." WHERE `name` = '1week'");
    $floor = $time - (floor($time / 604800) * 604800);
    if ($floor > 0) {
        $newUpdate = time() - $floor;
        $db->query('UPDATE `updates` SET `last` = '.$newUpdate." WHERE `name` = '1week'");
    }
	
}

Change and Add your Crons to the right section.

 

and here are the SQLs

CREATE TABLE `updates` (
  `name` varchar(255) NOT NULL DEFAULT '',
  `last` int(255) NOT NULL DEFAULT 60
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `updates`
--

INSERT INTO `updates` (`name`, `last`) VALUES
('1min', 1624438860),
('5min', 1624438800),
('1hour', 1624438800),
('1day', 1624406400),
('1month', 1541030400),
('1week', 1623888000);
COMMIT;

 

Edited by peterisgb
Link to comment
Share on other sites

3 hours ago, peterisgb said:

MagicTallGuy made this one quite a few years ago but has served me well since.

create file called cronless_crons.php and stick this in it.

<?php if ('/cronless_crons.php' == $_SERVER['PHP_SELF']) { exit; } if (!isset($set)) { $set = array(); $settq = $db->query('SELECT * FROM settings'); while ($r = $db->fetch_row($settq)) { $set[$r['conf_name']] = $r['conf_value']; } } // Minute $result2 = $db->query("SELECT * FROM updates WHERE name = '1min'"); $result1 = $db->fetch_row($result2); $hla1 = time() - $result1['last']; if ($hla1 > 60) { $n1 = floor($hla1 / 60); $db->query(sprintf('UPDATE `users` SET `hospital` = GREATEST(0, `hospital` - %u) WHERE `hospital` > 0', $n1)); $db->query(sprintf('UPDATE `users` SET `jail` = GREATEST(0, `jail` - %u) WHERE `jail` > 0', $n1)); // minute Cron stuff here $hc = $db->fetch_single($db->query('SELECT COUNT(`userid`) FROM `users` WHERE `hospital` > 0')); $jc = $db->fetch_single($db->query('SELECT COUNT(`userid`) FROM `users` WHERE `jail` > 0')); $db->query("UPDATE `settings` SET `conf_value` = '$hc' WHERE `conf_name` = 'hospital_count'"); $db->query("UPDATE `settings` SET `conf_value` = '$jc' WHERE `conf_name` = 'jail_count'"); $time = time(); $db->query('UPDATE `updates` SET `last` = '.$time." WHERE `name` = '1min'"); $floor = $time - (floor($time / 60) * 60); if ($floor > 0) { $newUpdate = time() - $floor; $db->query('UPDATE `updates` SET `last` = '.$newUpdate." WHERE `name` = '1min'"); } } // Five minute $result2 = $db->query("SELECT * FROM `updates` WHERE `name` = '5min'"); $result2 = $db->fetch_row($result2); $hla2 = time() - $result2['last']; if ($hla2 > 300) { $n = floor($hla2 / 300); $db->query('UPDATE `users` SET `brave` = LEAST(`brave` + (((`maxbrave` / 10) + 0.5) * '.$n.'), `maxbrave`), `hp` = LEAST(`hp` + ((`maxhp` / 12) * '.$n.'), `maxhp`), `energy` = IF(`donatordays`, LEAST(`energy` + ((`maxenergy` / 5) * '.$n.'), `maxenergy`), LEAST(`energy` + ((`maxenergy` / 10) * '.$n.'), `maxenergy`)), `will` = LEAST(`maxwill`, `will` + '.($n * 100).')'); $db->query('UPDATE `pets` SET `energy` = LEAST((`energy` + ((`maxenergy` / 30) + 2) * '.$n.'), maxenergy) WHERE (`energy` < `maxenergy`)'); $db->query('UPDATE `pets` SET `hp` = LEAST((`hp` + ((`maxhp` / 30) + 2) * '.$n.'), maxhp) WHERE (`hp` < `maxenergy`)'); // 5 minute cron stuff here $floor = $time - (floor($time / 300) * 300); if ($floor > 0) { $newUpdate = time() - $floor; $db->query('UPDATE `updates` SET `last` = '.$newUpdate." WHERE `name` = '5min'"); } } // 1 hour $result3 = $db->query("SELECT * FROM `updates` WHERE `name` = '1hour'"); $result3 = $db->fetch_row($result3); $hla3 = time() - $result3['last']; if ($hla3 > 3600) { $n3 = floor($hla3 / 3600); // Hourly cron stuff here if (17 == date('G')) { // 5pm crons here like workpayouts } if (8 == date('G')) { // 8am crons here } if (60 == $set['validate_period'] && $set['validate_on']) { $db->query('UPDATE users SET verified=0'); } $time = time(); $db->query('UPDATE `updates` SET `last` = '.$time." WHERE `name` = '1hour'"); $floor = $time - (floor($time / 3600) * 3600); if ($floor > 0) { $newUpdate = time() - $floor; $db->query('UPDATE `updates` SET `last` = '.$newUpdate." WHERE `name` = '1hour'"); } } // 1 day $result4 = $db->query("SELECT * FROM `updates` WHERE `name` = '1day'"); $result4 = $db->fetch_row($result4); $hla4 = time() - $result4['last']; if ($hla4 > 86400) { $n4 = floor($hla4 / 86400); $db->query('UPDATE `fedjail` SET `fed_days` = GREATEST(0, `fed_days` - '.$n4.')'); $q = $db->query('SELECT * FROM `fedjail` WHERE `fed_days` = 0'); $ids = array(); // Daily cron stuff here if (1 == date('j')) { // First of the month Crons here } $time = time(); $db->query('UPDATE `updates` SET `last` = '.$time." WHERE `name` = '1day'"); $floor = $time - (floor($time / 86400) * 86400); if ($floor > 0) { $newUpdate = time() - $floor; $db->query('UPDATE `updates` SET `last` = '.$newUpdate." WHERE `name` = '1day'"); } } // 1 Week $result5 = $db->query("SELECT * FROM `updates` WHERE `name` = '1week'"); $result5 = $db->fetch_row($result5); $hla5 = time() - $result5['last']; if ($hla5 > 604800) { $n5 = floor($hla5 / 604800); // Weekly Stuff Here if you have any $time = time(); $db->query('UPDATE `updates` SET `last` = '.$time." WHERE `name` = '1week'"); $floor = $time - (floor($time / 604800) * 604800); if ($floor > 0) { $newUpdate = time() - $floor; $db->query('UPDATE `updates` SET `last` = '.$newUpdate." WHERE `name` = '1week'"); } }



<?php

if ('/cronless_crons.php' == $_SERVER['PHP_SELF']) {
    exit;
}
if (!isset($set)) {
    $set = array();
    $settq = $db->query('SELECT * FROM settings');
    while ($r = $db->fetch_row($settq)) {
        $set[$r['conf_name']] = $r['conf_value'];
    }
}

// Minute
$result2 = $db->query("SELECT * FROM updates WHERE name = '1min'");
$result1 = $db->fetch_row($result2);
$hla1 = time() - $result1['last'];
if ($hla1 > 60) {
    $n1 = floor($hla1 / 60);
    $db->query(sprintf('UPDATE `users` SET `hospital` = GREATEST(0, `hospital` - %u) WHERE `hospital` > 0', $n1));
    $db->query(sprintf('UPDATE `users` SET `jail` = GREATEST(0, `jail` - %u) WHERE `jail` > 0', $n1));
    
    // minute Cron stuff here
    
    $hc = $db->fetch_single($db->query('SELECT COUNT(`userid`) FROM `users` WHERE `hospital` > 0'));
    $jc = $db->fetch_single($db->query('SELECT COUNT(`userid`) FROM `users` WHERE `jail` > 0'));
    $db->query("UPDATE `settings` SET `conf_value` = '$hc' WHERE `conf_name` = 'hospital_count'");
    $db->query("UPDATE `settings` SET `conf_value` = '$jc' WHERE `conf_name` = 'jail_count'");
    $time = time();
    $db->query('UPDATE `updates` SET `last` = '.$time." WHERE `name` = '1min'");
    $floor = $time - (floor($time / 60) * 60);
    if ($floor > 0) {
        $newUpdate = time() - $floor;
        $db->query('UPDATE `updates` SET `last` = '.$newUpdate." WHERE `name` = '1min'");
    }
}

// Five minute
$result2 = $db->query("SELECT * FROM `updates` WHERE `name` = '5min'");
$result2 = $db->fetch_row($result2);
$hla2 = time() - $result2['last'];
if ($hla2 > 300) {
    $n = floor($hla2 / 300);


	$db->query('UPDATE `users` SET `brave` = LEAST(`brave` + (((`maxbrave` / 10) + 0.5) * '.$n.'), `maxbrave`), `hp` = LEAST(`hp` + ((`maxhp` / 12) * '.$n.'), `maxhp`), `energy` = IF(`donatordays`, LEAST(`energy` + ((`maxenergy` / 5) * '.$n.'), `maxenergy`), LEAST(`energy` + ((`maxenergy` / 10) * '.$n.'), `maxenergy`)), `will` = LEAST(`maxwill`, `will` + '.($n * 100).')');
    $db->query('UPDATE `pets` SET `energy` = LEAST((`energy` + ((`maxenergy` / 30) + 2) * '.$n.'), maxenergy) WHERE (`energy` < `maxenergy`)');
    $db->query('UPDATE `pets` SET `hp` = LEAST((`hp` + ((`maxhp` / 30) + 2) * '.$n.'), maxhp) WHERE (`hp` < `maxenergy`)');
	
    // 5 minute cron stuff here

    $floor = $time - (floor($time / 300) * 300);
    if ($floor > 0) {
        $newUpdate = time() - $floor;
        $db->query('UPDATE `updates` SET `last` = '.$newUpdate." WHERE `name` = '5min'");
    }
}

// 1 hour
$result3 = $db->query("SELECT * FROM `updates` WHERE `name` = '1hour'");
$result3 = $db->fetch_row($result3);
$hla3 = time() - $result3['last'];
if ($hla3 > 3600) {
    $n3 = floor($hla3 / 3600);
    
	
	
    // Hourly cron stuff here
    
    
    if (17 == date('G')) {
        // 5pm crons here like workpayouts
    }
    
    
    if (8 == date('G')) {
        // 8am crons here
    }
    
    
    
    if (60 == $set['validate_period'] && $set['validate_on']) {
        $db->query('UPDATE users SET verified=0');
    }
    $time = time();
    $db->query('UPDATE `updates` SET `last` = '.$time." WHERE `name` = '1hour'");
    $floor = $time - (floor($time / 3600) * 3600);
    if ($floor > 0) {
        $newUpdate = time() - $floor;
        $db->query('UPDATE `updates` SET `last` = '.$newUpdate." WHERE `name` = '1hour'");
    }
}








// 1 day
$result4 = $db->query("SELECT * FROM `updates` WHERE `name` = '1day'");
$result4 = $db->fetch_row($result4);
$hla4 = time() - $result4['last'];
if ($hla4 > 86400) {
    $n4 = floor($hla4 / 86400);
    $db->query('UPDATE `fedjail` SET `fed_days` = GREATEST(0, `fed_days` - '.$n4.')');
    $q = $db->query('SELECT * FROM `fedjail` WHERE `fed_days` = 0');
    $ids = array();

	
	
	// Daily cron stuff here
    
    if (1 == date('j')) {

            // First of the month Crons here
        }

    $time = time();
    $db->query('UPDATE `updates` SET `last` = '.$time." WHERE `name` = '1day'");
    $floor = $time - (floor($time / 86400) * 86400);
    if ($floor > 0) {
        $newUpdate = time() - $floor;
        $db->query('UPDATE `updates` SET `last` = '.$newUpdate." WHERE `name` = '1day'");
    }
}





// 1 Week
$result5 = $db->query("SELECT * FROM `updates` WHERE `name` = '1week'");
$result5 = $db->fetch_row($result5);
$hla5 = time() - $result5['last'];
if ($hla5 > 604800) {
    $n5 = floor($hla5 / 604800);

    // Weekly Stuff Here if you have any
        

    $time = time();
    $db->query('UPDATE `updates` SET `last` = '.$time." WHERE `name` = '1week'");
    $floor = $time - (floor($time / 604800) * 604800);
    if ($floor > 0) {
        $newUpdate = time() - $floor;
        $db->query('UPDATE `updates` SET `last` = '.$newUpdate." WHERE `name` = '1week'");
    }
	
}

Change and Add your Crons to the right section.

 

and here are the SQLs

CREATE TABLE `updates` ( `name` varchar(255) NOT NULL DEFAULT '', `last` int(255) NOT NULL DEFAULT 60 ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `updates` -- INSERT INTO `updates` (`name`, `last`) VALUES ('1min', 1624438860), ('5min', 1624438800), ('1hour', 1624438800), ('1day', 1624406400), ('1month', 1541030400), ('1week', 1623888000); COMMIT;



CREATE TABLE `updates` (
  `name` varchar(255) NOT NULL DEFAULT '',
  `last` int(255) NOT NULL DEFAULT 60
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `updates`
--

INSERT INTO `updates` (`name`, `last`) VALUES
('1min', 1624438860),
('5min', 1624438800),
('1hour', 1624438800),
('1day', 1624406400),
('1month', 1541030400),
('1week', 1623888000);
COMMIT;

 

One completely untested update to this 🙂

Note: This uses a completely different table to the ones listed above. It stores times as date stamps (i.e., Y-m-d H:i:s).
 

<?php

if ('/cronless_crons.php' == $_SERVER['PHP_SELF']) {
    exit;
}
define('CHECK_TIMESTAMP_TABLE_EXISTENCE', true);

class CronlessCrons
{
    public database $db;
    private static ?self $inst = null;
    public array    $set    = [];
    private array   $timers = [];
    // cronless_crons.name -> duration in seconds
    private array $intervals = [
        '1m' => 60,
        '5m' => 300,
        '1h' => 3600,
        '1d' => 86400,
    ];

    public function __construct(database $db, array $set = [])
    {
        $this->db = $db;
        $this->setSettings($set);
        if (CHECK_TIMESTAMP_TABLE_EXISTENCE === true) {
            $this->checkTable();
        }
        $this->setTimers();;
        $this->checkTimers();
    }
    public static function getInstance(database $db, array $set): ?self
    {
        if (self::$inst === null) {
            self::$inst = new self($db, $set);
        }
        return self::$inst;
    }

    private function checkTable()
    {
        $getTable = $this->db->query('SELECT 1 FROM cronless_crons');
        if (!$this->db->num_rows($getTable)) {
            $this->db->query('
                CREATE TABLE cronless_crons (
                    id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
                    name VARCHAR(191) NOT NULL DEFAULT \'\',
                    last_ran TIMESTAMP NOT NULL DEFAULT \'0000-00-00 00:00:00\',
                    INDEX (name)
                );
            ');
            $values = '';
            foreach ($this->intervals as $interval) {
                $values .= ', (\'' . $interval . '\')';
            }
            $this->db->query('INSERT INTO cronless_crons (name) VALUES ' . substr($values, 2));
        }
    }

    private function setSettings(array $set = [])
    {
        if (empty($set)) {
            $set            = [];
            $selectSettings = $this->db->query('SELECT conf_name, conf_value FROM settings');
            while ($row = $this->db->fetch_row($selectSettings)) {
                $set[$row['conf_name']] = $row['conf_value'];
            }
        }
        $this->set = $set;
    }

    private function setTimers()
    {
        $selectTimers = $this->db->query('SELECT name, last_ran FROM cronless_crons');
        while ($row = $this->db->fetch_row($selectTimers)) {
            $this->timers[$row['name']] = $row['last_ran'];
        }
    }

    private function checkTimers()
    {
        $currentTime      = new DateTime('now');
        $currentTimeAsInt = $currentTime->format('U');
        foreach ($this->timers as $name => $timer) {
            $lastRan  = strtotime($timer);
            $interval = $this->intervals[$name];
            $deficit  = $currentTimeAsInt - $lastRan;
            if ($deficit > $interval) {
                $timesToRun = floor($deficit / $interval);
                $this->runCron($name, $timesToRun);
                $this->updateLastRan($currentTimeAsInt, $interval);
            }
        }
    }

    private function updateLastRan(int $currentTimeAsInt, int $interval)
    {
        $remaining = $currentTimeAsInt - (floor($currentTimeAsInt / $interval) * $interval);
        if ($remaining > 0) {
            $ran = $currentTimeAsInt - $remaining;
        } else {
            $ran = $currentTimeAsInt;
        }
        $ranAsDate = new DateTime('@' . $ran);
        $this->db->query('UPDATE cronless_crons SET last_ran = \'' . $ranAsDate . '\' WHERE name = \'' . $name . '\'');
    }

    private function runCron(string $name, int $multiplier)
    {
        switch ($name) {
            case '1m':
                $this->oneMinute($multiplier);
                break;
            case '5m':
                $this->fiveMinutes($multiplier);
                break;
            case '1h':
                $this->oneHour($multiplier);
                break;
            case '1d':
                $this->oneDay($multiplier);
                break;
        }
    }

    private function oneMinute(int $multiplier)
    {
        $this->updateHospJailCounters($multiplier);
    }

    private function updateHospJailCounters(int $multiplier)
    {
        $this->db->query(
            'UPDATE users SET 
                 hospital = GREATEST(hospital - ' . $multiplier . ', 0),
                 jail = GREATEST(jail - ' . $multiplier . ', 0)
                 WHERE hospital > 0 OR jail > 0;
        ');
        $getCnts = $this->db->query('
            SELECT SUM(IF(hospital > 0, 1, 0)) AS hospitalized,
                   SUM(IF(jail > 0, 1, 0)) AS imprisoned
            FROM users
            WHERE hospital > 0 OR jail > 0;
        ');
        $cnts    = $this->db->fetch_row($getCnts);
        $this->db->query('
            UPDATE settings SET
                conf_value = IF(conf_name = \'hospital_count\', ' . $cnts['hospitalized'] . ', conf_value),
                conf_value = IF(conf_name = \'jail_count\', ' . $cnts['imprisoned'] . ', conf_value)
                WHERE conf_name IN(\'hospital_count\', \'jail_count\');
        ');
    }

    private function fiveMinutes(int $multiplier)
    {
        $this->updateUserStatBars();
        $this->updatePetStatBars();
    }

    private function updateUserStatBars()
    {
        $this->db->query('
            UPDATE users SET
                brave = LEAST(brave + (((maxbrave / 10) + 0.5) * ' . $multiplier . '), maxbrave), 
                hp = LEAST(hp + ((maxhp / 12) * ' . $multiplier . '), maxhp), 
                energy = IF(donatordays > 0,
                    LEAST(energy + ((maxenergy / 5) * ' . $multiplier . '), maxenergy),
                    LEAST(energy + ((maxenergy / 10) * ' . $multiplier . '), maxenergy)
                ),
                will = LEAST(maxwill, will + ' . ($multiplier * 100) . ');
        ');
    }

    private function updatePetStatBars()
    {
        $this->db->query('
            UPDATE pets SET
                energy = LEAST((energy + ((maxenergy / 30) + 2) * ' . $multiplier . '), maxenergy),
                hp = LEAST((hp + ((maxhp / 30) + 2) * ' . $multiplier . '), maxhp)
                WHERE energy < maxenergy OR hp < maxhp;
        ');
    }

    private function oneHour(int $multiplier)
    {
        $this->processGangOrganisedCrimes();
        if ($this->set['validate_on'] > 0 && $this->set['validate_period'] == 60) {
            $this->resetValidation();
        }
    }

    private function processGangOrganisedCrimes()
    {
        $this->db->query('UPDATE gangs SET gangCHOURS = GREATEST(gangCHOURS - ' . $multiplier . ', 0) WHERE gangCRIME > 0');
        $getOrgCrimes = $this->db->query('
            SELECT gangID,ocSTARTTEXT, ocSUCCTEXT, ocFAILTEXT, ocMINMONEY, ocMAXMONEY, ocID, ocNAME
            FROM gangs AS g
            LEFT JOIN orgcrimes AS oc ON g.gangCRIME = oc.ocID
            WHERE g.gangCRIME > 0 AND g.gangCHOURS <= 0
        ');
        if ($this->db->num_rows($getOrgCrimes) > 0) {
            while ($row = $this->db->fetch_row($getOrgCrimes)) {
                if (mt_rand(0, 1) === 1) {
                    $money   = (int)(mt_rand($row['ocMINMONEY'], $row['ocMAXMONEY']));
                    $log     = str_replace('{muny}', $money, $row['ocSTARTTEXT'] . $row['ocSUCCTEXT']);
                    $outcome = 'success';
                } else {
                    $money   = 0;
                    $log     = $row['ocSTARTTEXT'] . $row['ocFAILTEXT'];
                    $outcome = 'failure';
                }
                $this->db->query('UPDATE gangs SET gangMONEY = gangMONEY + ' . $money . ', gangCRIME = 0 WHERE gangID = ' . $row['gangID']);
                $this->db->query('
                    INSERT INTO oclogs (oclOC, oclGANG, oclLOG, oclRESULT, oclMONEY, ocCRIMEN, ocTIME) VALUES
                    (' . $row['ocID'] . ', ' . $row['gangID'] . ', \'' . $this->db->escape($log) . '\', \'' . $outcome . '\', ' . $money . ', \'' . $row['ocNAME'] . '\', ' . time() . ')
                ');
                $oclID             = $this->db->insert_id();
                $selectGangMembers = $this->db->query('SELECT userid FROM users WHERE gang = ' . $row['gangID']);
                if ($this->db->num_rows($selectGangMembers)) {
                    while ($member = $this->db->fetch_row($selectGangMembers)) {
                        event_add($member['userid'], 'Your Gang\'s Organized Crime ' . ($outcome === 'success'
                                                       ? 'Succeeded'
                                                       : 'Failed') . '. Go <a href="oclog.php?ID=' . $oclID . '">here</a> to view the details.');
                    }
                }
            }
        }
    }

    private function resetValidation()
    {
        $this->db->query('UPDATE users SET verified = 0 WHERE verified <> 0');
    }

    private function oneDay(int $multiplier)
    {
        $this->payJobWages();
        $this->updateFedJail();
        $this->updateUserDailies();
        $this->processUserCourses();
        $this->cleanUpVotes();
    }

    private function payJobWages()
    {
        $this->db->query('
            UPDATE users AS u
            INNER JOIN userstats AS us ON u.userid = us.userid
            INNER JOIN jobranks AS jr ON jr.jrID = u.jobrank
            SET
                u.money = u.money + jr.jrPAY, u.exp = u.exp + (jr.jrPAY / 20),
                us.strength = (us.strength + 1) + jr.jrSTRG - 1,
                us.labour = (us.labour + 1) + jr.jrLABOURG - 1,
                us.IQ = (us.IQ+1) + jr.jrIQG - 1
            WHERE u.job > 0 AND u.jobrank > 0
        ');
    }

    private function updateFedJail()
    {
        $this->db->query('UPDATE fedjail SET fed_days = GREATEST(fed_days - ' . $multiplier . ', 0) WHERE fed_days > 0');
        $selectFedded = $this->db->query('SELECT fed_userid FROM fedjail WHERE fed_days <= 0');
        $ids          = [];
        if ($this->db->num_rows($selectFedded) > 0) {
            while ($row = $this->db->fetch_row($selectFedded)) {
                $ids[] = $row['fed_userid'];
            }
            $this->db->query('UPDATE users SET fedjail = 0 WHERE userid IN (' . implode(', ', $ids) . ')');
        }
        $this->db->query('DELETE FROM fedjail WHERE fed_days <= 0');
    }

    private function updateUserDailies()
    {
        $this->db->query('
            UPDATE users SET 
                daysingang = daysingang + IF(gang > 0, 1, 0),
                daysold = daysold + 1, boxes_opened = 0,
                mailban = mailban - IF(mailban > 0, 1, 0),
                donatordays = donatordays - IF(donatordays > 0, 1, 0),
                cdays = cdays - IF(course > 0, 1, 0),
                bankmoney = bankmoney + IF(bankmoney > 0, bankmoney / 50, 0),
                cybermoney = cybermoney + IF(cybermoney > 0, cybermoney / 100 * 7, 0)
        ');
    }

    private function processUserCourses()
    {
        $courses             = [];
        $selectUsersOnCourse = $this->db->query('SELECT userid, course FROM users WHERE cdays <= 0 AND course > 0');
        if ($this->db->num_rows($selectUsersOnCourse) > 0) {
            while ($row = $this->db->fetch_row($selectUsersOnCourse)) {
                if (!array_key_exists($row['course'], $courses)) {
                    $selectCourse            = $this->db->query('SELECT crID, crSTR, crGUARD, crLABOUR, crAGIL, crIQ, crNAME FROM courses WHERE crID = ' . $row['course']);
                    $course                  = $this->db->fetch_row($selectCourse);
                    $courses[$row['course']] = $course;
                } else {
                    $course = $courses[$row['course']];
                }
                $this->db->query('
                    INSERT INTO coursesdone (userid, courseid)
                    VALUES (' . $row['userid'] . ', ' . $row['course'] . ')
                ');
                $query = '';
                $event = '';
                if ($course['crSTR'] > 0) {
                    $query .= ', us.strength = us.strength + ' . $course['crSTR'];
                    $event .= ', ' . number_format($course['crSTR']) . ' strength';
                }
                if ($course['crAGIL'] > 0) {
                    $query .= ', us.agility = us.agility + ' . $course['crAGIL'];
                    $event .= ', ' . number_format($course['crAGIL']) . ' agility';
                }
                if ($course['crLABOUR'] > 0) {
                    $query .= ', us.labour = us.labour + ' . $course['crLABOUR'];
                    $event .= ', ' . number_format($course['crLABOUR']) . ' labour';
                }
                if ($course['crGUARD'] > 0) {
                    $query .= ', us.guard = us.guard + ' . $course['crGUARD'];
                    $event .= ', ' . number_format($course['crGUARD']) . ' guard';
                }
                if ($course['crIQ'] > 0) {
                    $query .= ', us.IQ = us.IQ + ' . $course['crIQ'];
                    $event .= ', ' . number_format($course['crIQ']) . ' IQ';
                }
                if ($query !== '') {
                    $this->db->query('
                        UPDATE users AS u
                        INNER JOIN userstats AS us ON u.userid = us.userid
                        SET u.course = 0' . $query . '
                        WHERE u.userid = ' . $row['userid']);
                    event_add($row['userid'], 'Congratulations, you\'ve completed the ' . $course['crNAME'] . ' and gained ' . $event);
                }
            }
        }
    }

    private function cleanUpVotes()
    {
        $this->db->query('TRUNCATE TABLE votes');
    }
}

/**
 * UGLY UGLY UGLY!
 * Set $db and $set properly! Don't be lazy and global scope 'em in
 */
global $db, $set;
CronlessCrons::getInstance($db, $set);

 

  • Like 1
Link to comment
Share on other sites

I made this a little bit ago and named it cron.php. I didnt put too much thought into it so it could be so much better.

Just add include_once "cron.php" in your globals and dont forget to add some settings values 

if (!defined('jdsf45tji'))
{
    echo 'This file cannot be accessed directly.';
    die;
}

$minute = 60;
$five = $minute * 5;
$hour = $minute * 60;
$day = $hour * 24;

$minute_last_run = $set['cron_min_last_run'];
$five_last_run = $set['cron_five_last_run'];
$hour_last_run = $set['cron_hour_last_run'];
$day_last_run = $set['cron_day_last_run'];

$time = time();

if(time() >= $minute_last_run) {
    $ran = false;
    $turns = floor((time() - $minute_last_run) / $minute);
    for ($i = 0; $i < $turns; $i++) {
        include "cron_minute.php";
        $ran = true;
    }
    if($ran) {
        $newTime = time() - ($time % $minute);
        $db->query("update settings set conf_value = $newTime where conf_name = 'cron_min_last_run'");
    }
}

if(time() >= $five_last_run) {
    $ran = false;
    $turns = floor((time() - $five_last_run) / $five);
    for ($i = 0; $i < $turns; $i++) {
        include "cron_fivemins.php";
        $ran = true;
    }
    if($ran) {
        $newTime = time() - ($time % $five);
        $db->query("update settings set conf_value = ". $newTime ." where conf_name = 'cron_five_last_run'");
    }
}

if(time() >= $hour_last_run) {
    $ran = false;
    $turns = floor((time() - $hour_last_run) / $hour);
    for ($i = 0; $i < $turns; $i++) {
        include "cron_hour.php";
        $ran = true;
    }
    if($ran) {
        $newTime = time() - ($time % $hour);
        $db->query("update settings set conf_value = ". $newTime ." where conf_name = 'cron_hour_last_run'");
    }
}

if(time() >= $day_last_run) {
    $ran = false;
    $turns = floor((time() - $day_last_run) / $day);
    for ($i = 0; $i < $turns; $i++) {
        include "cron_day.php";
        $ran = true;
    }
    if($ran) {
        $newTime = time() - ($time % $day);
        $db->query("update settings set conf_value = ". $newTime ." where conf_name = 'cron_day_last_run'");
    }
}

 

  • Like 1
Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...