Repository navigation
Expand file tree
/
Copy pathcron_queue_worker.php
More file actions
79 lines (69 loc) · 2.39 KB
/
Copy pathcron_queue_worker.php
File metadata and controls
79 lines (69 loc) · 2.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
<?php
/**
* Asynchronous Queue Worker Cron Job
*
* Recommended crontab (every minute):
* * * * * * cd /path/to/project && php cron_queue_worker.php >> /tmp/queue_cron.log 2>&1
*/
require_once __DIR__ . '/config.php';
use App\Core\Database;
use App\Core\Logger;
use App\Services\QueueWorker;
$db = Database::getInstance();
// Create execution log entry for crontab runs
$logId = null;
$cronJob = $db->row("SELECT id FROM cron_jobs WHERE slug = 'queue-worker'");
if ($cronJob) {
$db->execute(
"INSERT INTO cron_execution_logs (cron_job_id, status, started_at, triggered_by) VALUES (:jid, 'running', NOW(), 'crontab')",
[':jid' => $cronJob['id']]
);
$logId = $db->lastInsertId();
$db->execute(
"UPDATE cron_jobs SET last_status = 'running', updated_at = NOW() WHERE id = :id",
[':id' => $cronJob['id']]
);
}
$startTime = microtime(true);
$hasError = false;
$outputBuffer = '';
Logger::info("Queue worker cron started at " . date('Y-m-d H:i:s'));
$outputBuffer .= "=== Queue Worker Cron ===\n";
$outputBuffer .= "Started: " . date('Y-m-d H:i:s') . "\n\n";
try {
// Instantiate and run the worker
$worker = new QueueWorker();
$worker->run();
$outputBuffer .= "Queue worker executed successfully.\n";
} catch (\Throwable $e) {
$hasError = true;
Logger::error("Queue worker cron failed: " . $e->getMessage());
$outputBuffer .= "Error: " . $e->getMessage() . "\n" . $e->getTraceAsString() . "\n";
}
$duration = round(microtime(true) - $startTime, 2);
$outputBuffer .= "\nFinished: " . date('Y-m-d H:i:s') . "\n";
$outputBuffer .= "Duration: {$duration}s\n";
if ($cronJob && $logId) {
$db->execute(
"UPDATE cron_execution_logs SET status = :status, finished_at = NOW(), duration_seconds = :duration, output = :output, error_message = :err WHERE id = :id",
[
':status' => $hasError ? 'failed' : 'success',
':duration' => $duration,
':output' => $outputBuffer,
':err' => $hasError ? 'Queue worker execution encountered an error.' : null,
':id' => $logId
]
);
$db->execute(
"UPDATE cron_jobs SET last_status = :status, last_run_at = NOW(), updated_at = NOW() WHERE id = :id",
[
':status' => $hasError ? 'failed' : 'success',
':id' => $cronJob['id']
]
);
}
echo $outputBuffer;
if ($hasError) {
exit(1);
}
exit(0);