您好,我有一个浏览器游戏,其中各种玩家安排的动作可以持续一到两个小时。cronjob 每分钟检查所有已完成的操作(endtime <= unixtime() )并完成它们(向相关玩家提供奖励等);
最近发生了 - 比如说 - 100 个动作要完成,而 cronjob 任务 1 没有在一分钟内完成,所以 cronjob 任务 2 被触发,结果是所有动作都完成了两次。
我怎样才能避免这种情况再次发生?我必须为会话使用特定的事务隔离代码并保留要更新的行吗?
PHP 5.3.18 mysql 是 5.5.27 表引擎是 INNODB
当前每分钟调用一次的代码是这样的:
public function complete_expired_actions ( $charflag = false )
{
// Verifying if there are actions to complete...
$db = Database::instance();
$db -> query("set autocommit = 0");
$db -> query("begin");
$sql = "select * from
character_actions
where status = 'running'
and endtime <= unix_timestamp()";
$result = $db -> query ( $sql ) ;
// try-catch. Se si verifica un errore, l' azione che commette l' errore viene rollbackata
foreach ( $result as $row )
{
try
{
$o = $this->factory( $row -> action );
$o -> complete_action ( $row );
if ($row -> cycle_flag == FALSE)
{
// non aperta ad attacchi SQl-injection perchè i parametri non sono passati via request
if ( $charflag == true )
kohana::log( 'info', "-> Completing action: " . $row -> id . ' - ' . $row -> action . " for char: " . $row->character_id );
$db->query( "update character_actions set status = 'completed' where id = " . $row->id );
// in ogni caso invalida la sessione!
Cache_Model::invalidate( $row -> character_id );
}
$db->query('commit');
} catch (Kohana_Database_Exception $e)
{
kohana::log('error', kohana::debug( $e->getMessage() ));
kohana::log('error', 'An error occurred, rollbacking action:' . $row->action . '-' . $row->character_id );
$db->query("rollback");
}
}
$db->query("set autocommit = 1");