<?php<448901948@qq.com>
namespace think\queue;
use DateTime;
use think\facade\Env;
abstract class Job
{
protected $instance;
protected $queue;
protected $deleted = false;
protected $released = false;
abstract public function fire();
public function delete()
{
$this->deleted = true;
}
public function isDeleted()
{
return $this->deleted;
}
public function release($delay = 0)
{
$this->released = true;
}
public function isReleased()
{
return $this->released;
}
public function isDeletedOrReleased()
{
return $this->isDeleted() || $this->isReleased();
}
abstract public function attempts();
abstract public function getRawBody();
protected function resolveAndFire(array $payload)
{
list($class, $method) = $this->parseJob($payload['job']);
$this->instance = $this->resolve($class);
if ($this->instance) {
$this->instance->{$method}($this, $payload['data']);
}
}
protected function parseJob($job)
{
$segments = explode('@', $job);
return count($segments) > 1 ? $segments : [$segments[0], 'fire'];
}
protected function resolve($name)
{
if (strpos($name, '\\') === false) {
if (strpos($name, '/') === false) {
$module = '';
} else {
list($module, $name) = explode('/', $name, 2);
}
$name = Env::get('app_namespace') . ($module ? '\\' . strtolower($module) : '') . '\\job\\' . $name;
}
if (class_exists($name)) {
return new $name();
}
}
public function failed()
{
$payload = json_decode($this->getRawBody(), true);
list($class, $method) = $this->parseJob($payload['job']);
$this->instance = $this->resolve($class);
if ($this->instance && method_exists($this->instance, 'failed')) {
$this->instance->failed($payload['data']);
}
}
protected function getSeconds($delay)
{
if ($delay instanceof DateTime) {
return max(0, $delay->getTimestamp() - $this->getTime());
}
return (int) $delay;
}
protected function getTime()
{
return time();
}
public function getName()
{
return json_decode($this->getRawBody(), true)['job'];
}
public function getQueue()
{
return $this->queue;
}
}