I need to create a queue for my project but I am not totally sure how. My thought was, I could just add a mysql table for jobs, and run a cron job to check for new jobs every minute. Something like this:
// my cron process
// if there is a job with a status of "in-progress"
// do nothing
// else
// are there any jobs? get the oldest job in the table
// update the status to "in-progress"
// do whatever the job tells you
// delete the job
So that would basically run every minute. Is this an acceptable way to build a queue from scratch? I know running a job every minute may not be fast for some use cases but I think it is ok in my case.
Edit: I have been reading about RabbitMQ. Would this be a better option?
Edit2: If someone could explain to me why I got downvoted I would appreciate it. I seem to get downvoted immediately almost all the time so I want to know what I am doing wrong.
Edit3: Thanks everyone for the advice. I have learned a lot about queues and I think my final solution will be something along the lines of this:
/** THIS IS WHAT MY JOBS TABLE LOOKS LIKE */
// $sql = "CREATE TABLE IF NOT EXISTS `QueuedFileTransfers` (";
// $sql .= "`id` int(11) NOT NULL AUTO_INCREMENT, ";
// $sql .= "`file_name` VARCHAR(20) DEFAULT NULL, ";
// $sql .= "`status` VARCHAR(20) DEFAULT NULL, ";
// $sql .= "`attempts` INT DEFAULT NULL, ";
// $sql .= "`additional_data` VARCHAR(20) DEFAULT NULL, "; // store any relevant json data if the job fails
// $sql .= "`admin_notified` TINYINT(1) DEFAULT 0, ";
// $sql .= "`job_started_on` TIMESTAMP DEFAULT NULL, ";
// $sql .= "`job_finished_on` TIMESTAMP DEFAULT NULL, ";
// $sql .= "`created_on` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, ";
// $sql .= ") ENGINE = INNODB";
// check if there is a job that has been running for a long time, possibly stuck
// if there is a job with a status of "in-progress" and job_started_on > 15 min ago
// ??????
// check if there are any failed jobs to retry
// if there are any job with a status of "failed" and attempts < 3
// processJob($job);
// else if there is a job with a status of "pending", get the oldest one
// processJob($job)
// function processJob($job) {
// update job status to "in-progress" and job_started_on and attempts++
// check effected rows to make sure it updated
try {
// do the job
// update status to "completed"
} catch (Error $e) {
// change status to "failed"
// append error data to additional_data column
// if attempts = 3
// send email to administrator
// update admin_notified to 1
}
// }
Except refactored into OOP