Cron

The Cron module provides a comprehensive job scheduling system for FiveM resources with support for both cron expressions and interval-based scheduling.

schedule

Creates a job using a cron expression.

B2Lib.Cron.schedule(expression, callback, options)

Parameters:

  • expression (string): Cron expression (minute hour day month weekday)

  • callback (function): Function to execute

  • options (table, optional): Job configuration options

    • name (string): Job name for identification

    • context (table): Data passed to callback

    • maxRuns (number): Maximum number of executions

    • timeout (number): Execution timeout in milliseconds

    • maxRetries (number): Retry attempts on failure

    • retryDelay (number): Delay between retries in milliseconds

    • priority (number): Job priority (higher = more important)

    • tags (table): Array of tags for organization

    • onError (function): Error callback

    • onComplete (function): Completion callback

Returns: string - Job ID for management

Example:

-- Every 15 minutes
local jobId = B2Lib.Cron.schedule("*/15 * * * *", function(context, jobId)
    print("Running every 15 minutes")
end)

-- Daily at 2:30 AM with options
local dailyJob = B2Lib.Cron.schedule("30 2 * * *", function(context, jobId)
    print("Daily maintenance")
end, {
    name = "daily_maintenance",
    maxRuns = 30,
    onError = function(error, context, jobId)
        print("Job failed:", error)
    end
})

every

Creates a job that runs at regular intervals.

B2Lib.Cron.every(interval, callback, maxRuns, options)

Parameters:

  • interval (number): Interval in milliseconds

  • callback (function): Function to execute

  • maxRuns (number, optional): Maximum number of executions

  • options (table, optional): Additional job options

Returns: string - Job ID for management

Example:

-- Every 5 seconds
local jobId = B2Lib.Cron.every(5000, function(context, jobId)
    print("Every 5 seconds")
end)

-- Every minute, max 10 runs
local limitedJob = B2Lib.Cron.every(60000, function(context, jobId)
    print("Limited runs")
end, 10)

daily

Creates a job that runs daily at a specific time.

B2Lib.Cron.daily(hour, minute, callback, options)

Parameters:

  • hour (number): Hour (0-23)

  • minute (number): Minute (0-59)

  • callback (function): Function to execute

  • options (table, optional): Additional job options

Returns: string - Job ID for management

Example:

-- Daily at 2:30 PM
local dailyJob = B2Lib.Cron.daily(14, 30, function(context, jobId)
    print("Daily at 2:30 PM")
end)

weekly

Creates a job that runs weekly on a specific day and time.

B2Lib.Cron.weekly(weekday, hour, minute, callback, options)

Parameters:

  • weekday (number): Day of week (0=Sunday, 1=Monday, etc.)

  • hour (number): Hour (0-23)

  • minute (number): Minute (0-59)

  • callback (function): Function to execute

  • options (table, optional): Additional job options

Returns: string - Job ID for management

Example:

-- Every Monday at 9 AM
local weeklyJob = B2Lib.Cron.weekly(1, 9, 0, function(context, jobId)
    print("Weekly Monday meeting")
end)

monthly

Creates a job that runs monthly on a specific day and time.

B2Lib.Cron.monthly(day, hour, minute, callback, options)

Parameters:

  • day (number): Day of month (1-31)

  • hour (number): Hour (0-23)

  • minute (number): Minute (0-59)

  • callback (function): Function to execute

  • options (table, optional): Additional job options

Returns: string - Job ID for management

Example:

-- First day of month at midnight
local monthlyJob = B2Lib.Cron.monthly(1, 0, 0, function(context, jobId)
    print("Monthly report")
end)

after

Creates a one-time job that runs after a delay.

B2Lib.Cron.after(delay, callback, options)

Parameters:

  • delay (number): Delay in milliseconds

  • callback (function): Function to execute

  • options (table, optional): Additional job options

Returns: string - Job ID for management

Example:

-- Run once after 10 seconds
local delayedJob = B2Lib.Cron.after(10000, function(context, jobId)
    print("Delayed execution")
end)

setActive

Pauses or resumes a job.

B2Lib.Cron.setActive(jobId, active)

Parameters:

  • jobId (string): The job ID to modify

  • active (boolean): True to activate, false to pause

Returns: boolean - True if successful, false if job not found

remove

Removes a job from the scheduler.

B2Lib.Cron.remove(jobId)

Parameters:

  • jobId (string): The job ID to remove

Returns: boolean - True if successfully removed, false if job not found

executeNow

Manually executes a job immediately.

B2Lib.Cron.executeNow(jobId)

Parameters:

  • jobId (string): The job ID to execute

Returns: boolean - True if executed, false if job not found

getJob

Gets information about a specific job.

B2Lib.Cron.getJob(jobId)

Parameters:

  • jobId (string): The job ID to query

Returns: table|nil - Job information or nil if not found

  • id (string): Job ID

  • name (string): Job name

  • type (string): Job type (cron, interval, etc.)

  • active (boolean): Whether job is active

  • runCount (number): Number of times executed

  • lastRun (number): Last execution timestamp

  • nextRun (number): Next execution timestamp

  • averageExecutionTime (number): Average execution time in ms

getAllJobs

Gets information about all jobs.

B2Lib.Cron.getAllJobs()

Returns: table - Array of job information objects

updateContext

Updates the context data for a job.

B2Lib.Cron.updateContext(jobId, newContext)

Parameters:

  • jobId (string): The job ID to update

  • newContext (table): New context data

Returns: boolean - True if updated, false if job not found

getStats

Gets scheduler statistics.

B2Lib.Cron.getStats()

Returns: table - Scheduler statistics

  • totalJobs (number): Total number of jobs

  • activeJobs (number): Number of active jobs

  • totalExecutions (number): Total executions across all jobs

  • averageExecutionTime (number): Average execution time

  • memoryUsage (number): Estimated memory usage

cleanup

Removes completed and expired jobs.

B2Lib.Cron.cleanup()

Returns: number - Number of jobs cleaned up

getExpressions

Gets predefined cron expressions.

B2Lib.Cron.getExpressions()

Returns: table - Table of predefined expressions

  • EVERY_MINUTE: "* * * * *"

  • EVERY_5_MINUTES: "*/5 * * * *"

  • EVERY_15_MINUTES: "*/15 * * * *"

  • EVERY_30_MINUTES: "*/30 * * * *"

  • EVERY_HOUR: "0 * * * *"

  • EVERY_DAY: "0 0 * * *"

  • WEEKDAYS: "0 9 * * 1-5"

  • BUSINESS_HOURS: "0 9-17 * * 1-5"

  • MIDNIGHT: "0 0 * * *"

  • NOON: "0 12 * * *"

Example:

local expressions = B2Lib.Cron.getExpressions()
B2Lib.Cron.schedule(expressions.BUSINESS_HOURS, function()
    print("Business hours task")
end)

Configuration

Configure the cron system in config.lua:

Config.Cron = {
    maxJobs = 100,              -- Maximum number of concurrent jobs
    defaultTimeout = 30000,     -- Default job timeout in milliseconds
    cleanupInterval = 300000,   -- Cleanup interval in milliseconds
    maxRetries = 3,             -- Default maximum retries
    retryDelay = 5000,          -- Default retry delay in milliseconds
    enableStats = true,         -- Enable statistics tracking
    debugMode = false           -- Enable debug logging
}

Cron Expression Format

Cron expressions use five fields: minute hour day month weekday

Field Ranges

  • Minute: 0-59

  • Hour: 0-23 (24-hour format)

  • Day: 1-31

  • Month: 1-12

  • Weekday: 0-6 (0=Sunday, 1=Monday, etc.)

Special Characters

  • * - Any value (wildcard)

  • , - List separator (e.g., 1,3,5)

  • - - Range (e.g., 1-5)

  • / - Step values (e.g., */5 or 10-20/2)

Common Examples

  • * * * * * - Every minute

  • */5 * * * * - Every 5 minutes

  • 0 * * * * - Every hour

  • 0 0 * * * - Every day at midnight

  • 0 9 * * 1-5 - Weekdays at 9 AM

  • 0 0 1 * * - First day of every month

Troubleshooting

Jobs Not Executing

  1. Check that the cron expression is valid

  2. Verify the job is active with getJob()

  3. Ensure the callback function doesn't throw errors

  4. Check console for error messages

Performance Issues

  1. Limit the number of concurrent jobs

  2. Use appropriate intervals to avoid excessive execution

  3. Monitor execution times with getStats()

  4. Clean up completed jobs regularly

Memory Leaks

  1. Remove jobs when no longer needed

  2. Enable automatic cleanup in configuration

  3. Monitor job count with getAllJobs()

  4. Use cleanup() to remove expired jobs

Timing Issues

  1. Verify server time is correct for cron expressions

  2. Account for server timezone in scheduling

  3. Use intervals for precise timing requirements

  4. Test with executeNow() for immediate verification

Last updated