PHP

PHP Task Scheduler & Cron Jobs

Create an automated task scheduling system with cron expressions and job queue management.

PHPCronSchedulerQueue

Thumbnail for PHP Task Scheduler & Cron Jobs

Overview

Create an automated task scheduling system with cron expressions and job queue management.

Key Concepts

This project covers essential PHP development patterns including object-oriented programming, database interaction, and security best practices.

Getting Started

bash
# Clone the repository
git clone https://github.com/example/php-14-php-task-scheduler-cron-jobs
cd php-14-php-task-scheduler-cron-jobs

# Start local server
php -S localhost:8000

Core Implementation

php
<?php
declare(strict_types=1);

namespace App;

class PHPService
{
    private \PDO $db;

    public function __construct(\PDO $db)
    {
        $this->db = $db;
    }

    public function findAll(): array
    {
        $stmt = $this->db->query("SELECT * FROM items ORDER BY created_at DESC");
        return $stmt->fetchAll(\PDO::FETCH_ASSOC);
    }

    public function create(array $data): int
    {
        $stmt = $this->db->prepare(
            "INSERT INTO items (title, content, status) VALUES (:title, :content, :status)"
        );
        $stmt->execute([
            ':title'   => htmlspecialchars($data['title']),
            ':content' => htmlspecialchars($data['content']),
            ':status'  => $data['status'] ?? 'draft',
        ]);
        return (int) $this->db->lastInsertId();
    }

    public function update(int $id, array $data): bool
    {
        $stmt = $this->db->prepare(
            "UPDATE items SET title = :title, content = :content WHERE id = :id"
        );
        return $stmt->execute([
            ':id'      => $id,
            ':title'   => htmlspecialchars($data['title']),
            ':content' => htmlspecialchars($data['content']),
        ]);
    }
}
?>

Database Schema

sql
CREATE TABLE items (
    id INT AUTO_INCREMENT PRIMARY KEY,
    title VARCHAR(255) NOT NULL,
    content TEXT,
    status ENUM('draft', 'published', 'archived') DEFAULT 'draft',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    INDEX idx_status (status)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

Security Considerations

- All user inputs are sanitized with \htmlspecialchars()\ - Database queries use prepared statements to prevent SQL injection - CSRF tokens are validated on all form submissions - Sessions are configured with \httponly\ and \secure\ flags

Tags

- PHP - Cron - Scheduler - Queue

Related Projects

Comments (0)

Leave a Comment

No comments yet. Be the first to comment!