За последние 24 часа нас посетил 26691 программист и 1814 роботов. Сейчас ищут 1211 программистов ...

Cron запуск

Тема в разделе "PHP для новичков", создана пользователем Zloben, 5 янв 2017.

  1. Zloben

    Zloben Новичок

    С нами с:
    8 дек 2016
    Сообщения:
    27
    Симпатии:
    0
    Сайт: logosamber.com
    Движок: http://skripter.info/igry/games/8844-skript-brauzernoy-igry-football-manager-524-rus.html

    Там есть крон запуск моделяции матчей, он идет всего 5 минут, а мне надо, чтобы либо больше поставить, либо без ограничений. Насколько я понял за это отвечает класс AbstractJob... Но у меня не сильно получилось что-то исправить. Нужна ваша помощь. Спасибо за внимание!
     
  2. igordata

    igordata Суперстар
    Команда форума Модератор

    С нами с:
    18 мар 2010
    Сообщения:
    32.408
    Симпатии:
    1.768
    не понятно, как связаны крон и матчи.

    при запуске крона все матчи заканчиваются? ну поставь раз в час.
     
  3. Zloben

    Zloben Новичок

    С нами с:
    8 дек 2016
    Сообщения:
    27
    Симпатии:
    0
    После вашего вопроса для себя решил прочитать что такое крон(детально), это по сути запуск, допустим скрипта, в определенное время. Там есть отдельная кнопка в панели управления, которая отвечает за запуск модуляции матчей, подписана как крон запуск, сам я только осваиваю программирование, по этому нуждаюсь в вашей помощи. Облазил всю директорию и вроде нашел нужный исходник, вот только что-то исправить не получается. Я надеюсь более менее доступно объяснил. Суть такова:
    Я нажимаю кнопку генерации матчей, они начинают генерироваться и всё вроде хорошо, но сам матч рассчитан допустим на пол часа, а генерация моделирует 5 минут и останавливается...
     
  4. igordata

    igordata Суперстар
    Команда форума Модератор

    С нами с:
    18 мар 2010
    Сообщения:
    32.408
    Симпатии:
    1.768
    ну... надо наверное либо учиться и ковыряться, либо платить.

    А как она моделирует?
     
  5. Zloben

    Zloben Новичок

    С нами с:
    8 дек 2016
    Сообщения:
    27
    Симпатии:
    0
    Значит будем ковыряться.

    Движок не я писал, я лишь изучаю
     
  6. igordata

    igordata Суперстар
    Команда форума Модератор

    С нами с:
    18 мар 2010
    Сообщения:
    32.408
    Симпатии:
    1.768
    ты когда наковыряешь какие-то куски кода, то ты их сюда тащи. можно будет почитать.
     
  7. Zloben

    Zloben Новичок

    С нами с:
    8 дек 2016
    Сообщения:
    27
    Симпатии:
    0
    PHP:
    1. <?php
    2. /******************************************************
    3.  
    4.   WebSoccer.ML
    5.  
    6. ******************************************************/
    7.  
    8. /**
    9. * Base class of all jobs. Jobs are NOT Cron-Jobs, but simply scripts which are executed without break.
    10. *
    11. * @author Ingo Hofmann
    12. */
    13. abstract class AbstractJob {
    14.    
    15.     protected $_websoccer;
    16.     protected $_db;
    17.     protected $_i18n;
    18.    
    19.     private $_id;
    20.     private $_interval;
    21.    
    22.     /**
    23.      *
    24.      * @param WebSoccer $websoccer request context.
    25.      * @param DbConnection $db database connection-
    26.      * @param I18n $i18n messages context.
    27.      * @param string $jobId Job ID as defined at jobs.xml.
    28.      * @param $errorOnAlreadyRunning boolean TRUE if error shall occur on init time when an instance of this job is already running.
    29.      */
    30.     function __construct(WebSoccer $websoccer, DbConnection $db, I18n $i18n, $jobId, $errorOnAlreadyRunning = TRUE) {
    31.         $this->_websoccer = $websoccer;
    32.         $this->_db = $db;
    33.         $this->_i18n = $i18n;
    34.        
    35.         $this->_id = $jobId;
    36.        
    37.         $xmlConfig = $this->getXmlConfig();
    38.        
    39.         // check if another instance is running (consider timeout of 5 minutes)
    40.         if ($errorOnAlreadyRunning) {
    41.             $initTime = (int) $xmlConfig->attributes()->inittime;
    42.             $now = $websoccer->getNowAsTimestamp();
    43.             $timeoutTime = $now - 5 * 60;
    44.             if ($initTime > $timeoutTime) {
    45.                 //throw new Exception('Another instance of this job is already running.');
    46.                 echo 'Another instance of this job is already running.';
    47.             }
    48.             $this->replaceAttribute('inittime', $now);
    49.         }
    50.        
    51.         $interval = (int) $xmlConfig->attributes()->interval;
    52.         $this->_interval = $interval * 20;
    53.        
    54.         ignore_user_abort(TRUE);
    55.         // run possibly forever
    56.         set_time_limit(0);
    57.        
    58.         // enable garbage collection (in case it is disabled by default)
    59.         gc_enable();
    60.     }
    61.    
    62.     /**
    63.      * Destructor resets marker for checking the only instance.
    64.      */
    65.     function __destruct() {
    66.         // little hack: set the ping so that 'last execution' also works for external job executions.
    67.         // Better solution would be a AOP implementation which creates an interceptor for execute() function,
    68.         // but for now this should also lead to the same behavior.
    69.         $this->_ping($this->_websoccer->getNowAsTimestamp());
    70.        
    71.         //$this->replaceAttribute('inittime', 0);
    72.     }
    73.    
    74.     /**
    75.      * Starts the job. Pauses the script after each iteration.
    76.      */
    77.     public function start() {
    78.        
    79.         // reset stopping
    80.         $this->replaceAttribute('stop', '0');
    81.         $this->replaceAttribute('error', '');
    82.         $this->_ping(0);
    83.        
    84.         do {
    85.            
    86.             $xmlConfig = $this->getXmlConfig();
    87.             $stop = (int) $xmlConfig->attributes()->stop;
    88.             if ($stop === 1) {
    89.                 $this->stop();
    90.             }
    91.            
    92.             $now = $this->_websoccer->getNowAsTimestamp();
    93.            
    94.             // check if lastping has been set by another job. then this job became obsolete
    95.             $lastPing = (int) $xmlConfig->attributes()->last_ping;
    96.             if ($lastPing > 0) {
    97.                 $myOwnLastPing = $now - $this->_interval + 5; //plus tolerance
    98.                 if ($lastPing > $myOwnLastPing) {
    99.                     exit;
    100.                 }
    101.             }
    102.            
    103.             $this->_ping($now);  
    104.                
    105.             try {
    106.                 // reconnect to db
    107.                 $this->_db->close();
    108.                 $this->_db->connect($this->_websoccer->getConfig('db_host'),
    109.                     $this->_websoccer->getConfig('db_user'),
    110.                     $this->_websoccer->getConfig('db_passwort'),
    111.                     $this->_websoccer->getConfig('db_name'));
    112.                
    113.                 $this->execute();
    114.                
    115.                 // force freeing memory by garbage collector
    116.                 gc_collect_cycles();
    117.             } catch (Exception $e) {
    118.                 $this->replaceAttribute('error', $e->getMessage());
    119.                 $this->stop();
    120.             }
    121.                
    122.             $this->_db->close();
    123.            
    124.             sleep($this->_interval);
    125.         } while(true);
    126.     }
    127.    
    128.     /**
    129.      * Stops the job.
    130.      */
    131.     public function stop() {
    132.         $this->replaceAttribute('stop', '1');
    133.        
    134.         exit;
    135.     }
    136.    
    137.     private function _ping($time) {
    138.         $this->replaceAttribute('last_ping', $time);
    139.     }
    140.    
    141.     private function getXmlConfig() {
    142.         $xml = simplexml_load_file(JOBS_CONFIG_FILE);
    143.         $xmlConfig = $xml->xpath('//job[@id = \''. $this->_id . '\']');
    144.         if (!$xmlConfig) {
    145.             throw new Exception('Job config not found.');
    146.         }
    147.        
    148.         return $xmlConfig[0];
    149.     }
    150.    
    151.     private function replaceAttribute($name, $value) {
    152.        
    153.         // lock file for this transaction
    154.         $fp = fopen(BASE_FOLDER . '/admin/config/lockfile.txt', 'r');
    155.         flock($fp, LOCK_EX);
    156.        
    157.         $xml = simplexml_load_file(JOBS_CONFIG_FILE);
    158.         if ($xml === FALSE) {
    159.            
    160.             $errorMessages = '';
    161.             $errors = libxml_get_errors();
    162.             foreach ($errors as $error) {
    163.                 $errorMessages = $errorMessages . "\n" . $error;
    164.             }
    165.             throw new Exception('Job with ID \'' . $this->_id . '\': Could not update attribute \'' . $name . '\' with value \'' . $value . '\'. Errors: ' . $errorMessages);
    166.         }
    167.         $xmlConfig = $xml->xpath('//job[@id = \''. $this->_id . '\']');
    168.         $xmlConfig[0][$name] = $value;
    169.         $successfulWritten = $xml->asXML(JOBS_CONFIG_FILE);
    170.         if (!$successfulWritten) {
    171.             throw new Exception('Job with ID \'' . $this->_id . '\': Could not save updated attribute \'' . $name . '\' with value \'' . $value . '\'.');
    172.         }
    173.        
    174.         // unlock
    175.         flock($fp, LOCK_UN);
    176.     }
    177.    
    178.     /**
    179.      * Execute this job by calling program code.
    180.      */
    181.     abstract function execute();
    182. }
    183.  
    184. ?>
    Вот например
    --- Добавлено ---
    Я так понял это класс отвечаешь за старт моделяции.
     
  8. igordata

    igordata Суперстар
    Команда форума Модератор

    С нами с:
    18 мар 2010
    Сообщения:
    32.408
    Симпатии:
    1.768
    ну попробуй тут изменить что-то
     
  9. Zloben

    Zloben Новичок

    С нами с:
    8 дек 2016
    Сообщения:
    27
    Симпатии:
    0
    Там уже ковырял)
     
  10. igordata

    igordata Суперстар
    Команда форума Модератор

    С нами с:
    18 мар 2010
    Сообщения:
    32.408
    Симпатии:
    1.768
    ну и кроном запускать реже