-
Choose a snake_case name matching the action (e.g. sync_dns_records).
Verify no file with that name exists in the Tasks/ directory before continuing.
-
Create the task file in the Tasks/ directory with this exact skeleton:
<?php
require_once '/home/my/include/functions.inc.php';
function <name>($args)
{
global $worker_db, $global, $influx_v2_database, $memcache, $redis;
return true;
}
Remove require_once only if the function needs no PEAR DB / MyAdmin\App access (rare — see bandwidth.php).
-
Add database queries using one of these two patterns — pick the one that matches your access needs:
Workerman fluent (preferred for simple SELECTs):
$row = $worker_db->select('*')->from('vps')->where('id = :id')
->bindValues(['id' => $args['id']])->row();
PEAR DB via MyAdmin\App::db() (needed when session/accounts state is also required — App::session(), App::accounts()):
use MyAdmin\App;
$db = App::db();
$db->query("SELECT * FROM vps WHERE id=".(int)$args['id']);
$db->next_record(MYSQL_ASSOC);
$row = $db->Record;
The container is initialised once per worker process when functions.inc.php first loads — never call App::setContainer() inside a task. Do not reach into $GLOBALS['tf'] directly; that path is being removed.
-
Add a GlobalData CAS lock if the task must not run concurrently per resource:
$lockVar = '<name>_' . $args['id'];
if (!isset($global->$lockVar)) {
$global->$lockVar = 0;
}
if (!$global->cas($lockVar, 0, time())) {
return 'locked';
}
$global->$lockVar = 0;
-
Write to InfluxDB only when the task collects metrics:
if (INFLUX_V2 === true) {
$influx_v2_database->write(
'<measurement>,tag1=val1 field1=' . (int)$value
);
$influx_v2_database->close();
}
-
Wrap the body in try/catch for any external I/O:
try {
} catch (\Exception $e) {
error_log('<name> Got Exception ' . $e->getCode() . ': ' . $e->getMessage());
\Workerman\Worker::safeEcho('<name> Got Exception ' . $e->getCode() . ': ' . $e->getMessage() . "\n");
return false;
}
-
Dispatch the task from Applications/Chat/Events.php or another task using the async pattern:
$conn = new \Workerman\Connection\AsyncTcpConnection('Text://127.0.0.1:2208');
$conn->send(json_encode(['type' => '<name>', 'args' => $args]));
$conn->onMessage = function ($c, $result) use ($conn) { $conn->close(); };
$conn->connect();
Verify the task name string matches the file/function name exactly.
-
Run a style check before finishing:
php vendor/bin/php-cs-fixer fix --dry-run Tasks/
php vendor/bin/php-cs-fixer fix Tasks/