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 executeoptions
(table, optional): Job configuration optionsname
(string): Job name for identificationcontext
(table): Data passed to callbackmaxRuns
(number): Maximum number of executionstimeout
(number): Execution timeout in millisecondsmaxRetries
(number): Retry attempts on failureretryDelay
(number): Delay between retries in millisecondspriority
(number): Job priority (higher = more important)tags
(table): Array of tags for organizationonError
(function): Error callbackonComplete
(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 millisecondscallback
(function): Function to executemaxRuns
(number, optional): Maximum number of executionsoptions
(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 executeoptions
(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 executeoptions
(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 executeoptions
(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 millisecondscallback
(function): Function to executeoptions
(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 modifyactive
(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 IDname
(string): Job nametype
(string): Job type (cron, interval, etc.)active
(boolean): Whether job is activerunCount
(number): Number of times executedlastRun
(number): Last execution timestampnextRun
(number): Next execution timestampaverageExecutionTime
(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 updatenewContext
(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 jobsactiveJobs
(number): Number of active jobstotalExecutions
(number): Total executions across all jobsaverageExecutionTime
(number): Average execution timememoryUsage
(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
or10-20/2
)
Common Examples
* * * * *
- Every minute*/5 * * * *
- Every 5 minutes0 * * * *
- Every hour0 0 * * *
- Every day at midnight0 9 * * 1-5
- Weekdays at 9 AM0 0 1 * *
- First day of every month
Troubleshooting
Jobs Not Executing
Check that the cron expression is valid
Verify the job is active with
getJob()
Ensure the callback function doesn't throw errors
Check console for error messages
Performance Issues
Limit the number of concurrent jobs
Use appropriate intervals to avoid excessive execution
Monitor execution times with
getStats()
Clean up completed jobs regularly
Memory Leaks
Remove jobs when no longer needed
Enable automatic cleanup in configuration
Monitor job count with
getAllJobs()
Use
cleanup()
to remove expired jobs
Timing Issues
Verify server time is correct for cron expressions
Account for server timezone in scheduling
Use intervals for precise timing requirements
Test with
executeNow()
for immediate verification
Last updated