Skip to content

Commit e139d9b

Browse files
committed
#1.2.0 Added subscribe to crontab and add to cronjob support. See readme for usage info.
1 parent db41f37 commit e139d9b

File tree

6 files changed

+192
-2
lines changed

6 files changed

+192
-2
lines changed

classes/core_cron.php

Lines changed: 124 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,124 @@
1+
<?php
2+
class Core_Cron{
3+
4+
public static function update_interval($code)
5+
{
6+
$bind = array(
7+
'record_code' => $code,
8+
'now' => Phpr_DateTime::now()->toSqlDateTime()
9+
);
10+
Db_DbHelper::query('insert into core_cron_table (record_code, updated_at) values (:record_code, now()) on duplicate key update updated_at =:now', $bind);
11+
}
12+
13+
public static function get_interval($code)
14+
{
15+
$interval = Db_DbHelper::scalar('select updated_at from core_cron_table where record_code =:record_code', array('record_code'=>$code));
16+
if (!$interval)
17+
{
18+
self::update_interval($code);
19+
$interval = Phpr_DateTime::now()->toSqlDateTime();
20+
}
21+
22+
return $interval;
23+
}
24+
25+
public static function execute_cron()
26+
{
27+
try
28+
{
29+
// Jobs are one off executions
30+
self::execute_cronjobs();
31+
32+
// Tables are regular executions
33+
self::execute_crontabs();
34+
}
35+
catch (Exception $ex)
36+
{
37+
echo $ex->getMessage();
38+
Phpr::$events->fire_event('core:on_execute_cron_exception',$ex);
39+
}
40+
}
41+
42+
// Usage:
43+
// Core_Cron::queue_job('User_Model::static_method', array('param1', 'param2', 'param3'));
44+
// Executes:
45+
// User_Model::static_method('param1', 'param2', 'param3');
46+
public static function queue_job($handler_name, $param_data=array())
47+
{
48+
$bind = array(
49+
'handler_name' => $handler_name,
50+
'param_data' => serialize($param_data),
51+
'now' => Phpr_DateTime::now()->toSqlDateTime()
52+
);
53+
Db_DbHelper::query('insert into core_cron_jobs (handler_name, param_data, created_at) values (:handler_name, :param_data, now())', $bind);
54+
}
55+
56+
private static function execute_cronjobs()
57+
{
58+
// Worker can perform only 5 jobs per run
59+
//
60+
$jobs = Db_DbHelper::objectArray('select * from core_cron_jobs order by created_at asc limit 5');
61+
62+
foreach ($jobs as $job)
63+
{
64+
Db_DbHelper::query('delete from core_cron_jobs where id=:id limit 1', array('id'=>$job->id));
65+
66+
$params = $job->param_data ? unserialize($job->param_data) : array();
67+
$parts = explode('::', $job->handler_name);
68+
if (count($parts) < 1)
69+
continue;
70+
71+
$model_class = $parts[0];
72+
if (!isset($parts[1]))
73+
return;
74+
75+
$method_name = $parts[1];
76+
77+
if (method_exists($model_class, $method_name))
78+
call_user_func_array(array($model_class, $method_name), $params);
79+
}
80+
}
81+
82+
private static function execute_crontabs()
83+
{
84+
$modules = Core_ModuleManager::listModules();
85+
foreach ($modules as $module)
86+
{
87+
if(!method_exists($module, 'subscribe_crontab'))
88+
continue;
89+
90+
$module_id = $module->getId();
91+
$cron_items = $module->subscribe_crontab();
92+
93+
if (!is_array($cron_items))
94+
continue;
95+
96+
foreach ($cron_items as $code=>$options)
97+
{
98+
$code = $module_id . '_' . $code;
99+
if (!isset($options['interval']) || !isset($options['method']))
100+
continue;
101+
102+
$last_exec = Phpr_DateTime::parse(self::get_interval($code), Phpr_DateTime::universalDateTimeFormat);
103+
$next_exec = $last_exec->addMinutes($options['interval']);
104+
$can_execute = Phpr_DateTime::now()->compare($next_exec);
105+
106+
if ($can_execute == -1)
107+
continue;
108+
109+
try
110+
{
111+
$method = $options['method'];
112+
if ($module->$method())
113+
self::update_interval( $code );
114+
115+
}
116+
catch (Exception $ex)
117+
{
118+
echo "Error in cron: " . $code . PHP_EOL;
119+
echo $ex->getMessage();
120+
}
121+
}
122+
}
123+
}
124+
}

classes/core_cronmanager.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ public static function access_allowed()
1919

2020
return true;
2121
}
22+
2223
}
2324

2425
?>

cron.php

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
<?php
2+
/**
3+
* Execute cron as a standalone
4+
*
5+
* Example usage:
6+
* /usr/local/bin/php -q /home/YOUR_USERNAME/public_html/modules/core/cron.php
7+
*/
8+
9+
chdir(dirname(__FILE__));
10+
$APP_CONF = array();
11+
$Phpr_InitOnly = true;
12+
include '../../index.php';
13+
Core_Cron::execute_cron();

readme.md

Lines changed: 39 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,4 +5,42 @@ This updated module can be installed using the updatecenter module: https://gith
55
####Updates
66
- 1.12.0 Start community updates (github:damanic). Added events to update manager 'core:onAfterGetModuleVersions', 'core:onGetBlockedUpdateModules', 'core:onAfterRequestUpdateList'
77
- 1.12.1 Minor update to Core_UpdateManager: Added event core:onFetchSoftwareUpdateFiles. Updated PclZip to 2.8.2
8-
- 1.12.2 Added the force parameter to update request events.
8+
- 1.12.2 Added the force parameter to update request events.
9+
- 1.2.0 Added subscribe to crontab and add to cronjob support
10+
11+
###New Cron Features
12+
####Execute cron as a standalone
13+
Example trigger to add to your system schedule: `/usr/local/bin/php -q /home/YOUR_USERNAME/public_html/modules/core/cron.php`
14+
####Subscribe a task to the cron tab
15+
In any module add the function subscribe_crontab(). Eg.
16+
17+
```
18+
class xCustom_Module{
19+
20+
protected function createModuleInfo (){
21+
return new Core_ModuleInfo(
22+
'Module',
23+
'Example for you',
24+
'The dude');
25+
}
26+
27+
public function subscribe_crontab(){
28+
return array(
29+
'update_products' => array('method'=>'update_products', 'interval'=>1440), // Every 24 hours
30+
);
31+
}
32+
33+
public function update_products(){
34+
traceLog('I've been hit by cron interval');
35+
}
36+
37+
public function background_task($param1,$param2){
38+
traceLog('I've been hit by cron job');
39+
}
40+
}
41+
```
42+
43+
####Add a job to a que so that it is processed in the background cron job process without delaying the currently executing script.
44+
Anywhere in your code you can que a task and it will be executed as soon as possible. Example:
45+
`Core_Cron::queue_job('xCustom_Module::background_task',array($param1, $param2 ));`
46+

updates/1.2.0.sql

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
CREATE TABLE `core_cron_jobs` (
2+
`id` int(11) NOT NULL AUTO_INCREMENT,
3+
`handler_name` varchar(100) DEFAULT NULL,
4+
`param_data` text,
5+
`created_at` datetime DEFAULT NULL,
6+
PRIMARY KEY (`id`)
7+
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
8+
9+
CREATE TABLE `core_cron_table` (
10+
`record_code` varchar(50) NOT NULL,
11+
`updated_at` datetime DEFAULT NULL,
12+
PRIMARY KEY (`record_code`)
13+
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

updates/version.dat

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -460,4 +460,5 @@
460460
#1.12.0 Start community updates (github:damanic). Added events to update manager 'core:onAfterGetModuleVersions', 'core:onGetBlockedUpdateModules', 'core:onAfterRequestUpdateList'
461461
#1.12.1 Minor update to Core_UpdateManager: Added event core:onFetchSoftwareUpdateFiles. Updated PclZip to 2.8.2
462462
#1.12.2 Added the force parameter to update request events.
463-
#1.12.3 Minor fix in core_modulemanager. This resolves damanic/ls1-module-updatecenter#1
463+
#1.12.3 Minor fix in core_modulemanager. This resolves damanic/ls1-module-updatecenter#1
464+
#1.2.0|@1.2.0 Added subscribe to crontab and add to cronjob support

0 commit comments

Comments
 (0)