PHP code example of maxwellhealth / taskr

1. Go to this page and download the library: Download maxwellhealth/taskr library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

maxwellhealth / taskr example snippets




use Taskr\HandlerAbstract;
use Taskr\Task;

class MyHandler extends HandlerAbstract
{
    private $collection;
    private $logPath;

    public function __construct(\MongoCollection $collection)
    {
        $this->collection = $collection;
        $this->logPath = '/tmp/';
    }

    public function writeLog($message)
    {
        file_put_contents($this->logPath . $this->getTaskId(true) . '.log', $message . "\n", FILE_APPEND);
    }

    public function readLog($offset = 0)
    {
        $handle = fopen($this->logPath . $this->getTaskId(true) . '.log', 'r');

        $contents = '';

        fseek($handle, $offset);

        while (!feof($handle)) {
            $contents .= fgets($handle, 4096);
        }

        return $contents;
    }

    public function set($key, $value)
    {
        $this->collection->update([
            'taskId' => $this->getTaskId(true),
        ], [
            '$set' => ['taskId' => $this->getTaskId(true), $key => $value],
        ], ['upsert' => true]);
    }

    public function get($key = null, $default = null)
    {
        $fields = [];

        if (!is_null($key)) {
            $fields[$key] = true;
        }

        $doc = $this->collection->findOne(['taskId' => $this->getTaskId(true)], $fields);

        if (!$doc) {
            return $default;
        }

        if (is_null($key)) {
            return $doc;
        }

        if (!array_key_exists($key, $doc)) {
            return $default;
        }

        return $doc[$key];
    }

    public function setValues(array $values)
    {
        $values['taskId'] = $this->getTaskId(true);

        $this->collection->update([
            'taskId' => $this->getTaskId(true),
        ], [
            '$set' => $values,
        ], ['upsert' => true]);
    }
}

$mongo = new \MongoClient();
$db = $mongo->taskr;
$collection = $db->tasks;

$handler = new MyHandler($collection);

$task = new Task($handler, function(MyHandler $handler) {
    $handler->writeLog('The task has started');
    sleep(2);
    $handler->complete();
});

$task->run();