Schedule a Job with CronJob
A cron job allows you to run repetitive actions on a predetermined schedule. There are two steps to create a cron job:
- Define a new Type and implement the logic you want to execute on a schedule.
- Create the batch job by specifying which method to invoke and its schedule.
In this example, you create a cron job to simulate recording the temperature on a given city every five minutes.
Define and implement the logic
In this example, you store temperature data for a city at a point in time. Start by creating a new Type:
/**
* Temperature.c3typ
*/
entity type Temperature schema name "TEMPERATURE" {
time: !datetime
city: !string
value: !double
recordTemperature: function(city: string = "San Francisco") js server
}Next, implement the logic that records the temperature:
/** Temperature.js
*
* @param {string} city
*/
function recordTemperature(city) {
Temperature.make({
time: new Date().toISOString(),
city: city,
value: Math.floor(Math.random() * 100)
}).create();
}Create a batch job from console
After implementing the logic and deploying the Temperature type, you are ready to create a cron job.
You can create a cron job either as part of your application logic, in the C3 AI Console, or as seed data. In the C3 AI Console, run the following code:
// The Type and method to run
var action = ActionRef.fromTypeAction(Temperature, 'recordTemperature');
// On which schedule to run the action
var schedule = CronSchedule.make({
startTime: null, // Start immediately
endTime: null, // Run indefinitely
cronExpression: "0 0/5 * * * ?", // Every five minutes
timeZone: "America/Los_Angeles" // (Optional) Pacific Time
});
// Create and persist the job
var job = CronJob.make({
name: "Capture weather data",
description: "Collects weather data for San Jose",
action: action, // The method to run
inputs: {city: "San Jose"}, // Parameters to the method
concurrent: false, // Only run one instance at a time
inactive: false, // Start running immediately
scheduleDef: schedule
}).create();Work with time zones in a cron job
Cron jobs support time zones through the timeZone field in the CronSchedule Type. By default, cron jobs run in UTC time, but you can specify a different time zone so that the job executes at local times. If you do not specify a time zone, cron jobs default to UTC time.
To set a timezone, specify the time zone ID in the schedule definition. For example, refer to the line timeZone: "America/Los_Angeles" in the previous code snippet. When you create or update cron jobs, the C3 Agentic AI Platform automatically validates time zone IDs. Invalid time zone IDs result in an error.
You can use any standard IANA Time Zone Database identifiers. To view all timezone IDs in the system, run the following command in C3 AI Console:
TimeZone.listIds()Time zones that observe daylight savings time (DST), such as America/New_York, automatically adjust for DST transitions. For example, a job scheduled for 9:00 AM runs at 9:00 AM local time year-round.
Create a batch job with seed data
It is recommended to create a cron job as seed data in your application package. This is useful when you want the job to run when the application package is deployed into a new environment.
In this case, you can add the cron job definition in JSON format to {package}/seed/CronJob/{name}.json:
{
"id" : "weather-collect-sj",
"name" : "CollectWeatherData",
"description" : "Collects weather data for San Jose",
"action" : {
"typeName" : "Temperature",
"actionName" : "recordTemperature",
},
"inputs": {
"city": "San Jose"
},
"concurrent": false,
"inactive": false,
"scheduleDef" : {
"startTime": null,
"endTime": null,
"cronExpression" : "0 0/5 * * * ?"
}
}Note: You must explicitly upsert seed data. When you create a cron job from the seed folder you must call Pkg.upsertAllSeed(). This will collect all seed data from the package and persist the seeded objects.
Monitor the job
You can check for the status of a cron job in the C3 AI Console:
var job = CronJob.get(/*jobId*/);
// Get information about executions
job.lastRuns();
// Pause the job
job.pause();
// Resumes the job
job.resume();Troubleshoot errors
When troubleshooting for errors, start by looking at the list of errors associated with the job:
var job = CronJob.get(/*jobId*/);
// Check if there are any errors
job.lastErrors();One way to troubleshoot the logic is to invoke directly the method the cron job is scheduled to run. This allows you to see if the method runs successfully and to troubleshoot errors.
When you find the root cause of the problem, update the logic in your application package to fix it, provision the application package with the latest changes, and resume the job if you paused it.
All cron jobs are added to the CronQueue for asynchronous processing, so you can also monitor the status of the queue. In the C3 AI Console, run:
// Get a report on the queue status
c3QReport(CronQueue /*Which queue*/,
true /* Group by object */,
true /* Group by context */)
// Check if there are any entries in the queue with errors
c3QErrs(CronQueue)Schedule format
The schedule of a cron job is specified using a Cron expression. This expression specifies how often the action needs to run. Here are some examples:
| Expression | Triggered |
|---|---|
0 15 10 \* \* ? | 10:15 AM every day |
0 0/5 14 \* \* ? | Every 5 minutes starting at 2 PM and ending at 2:55 PM, every day |
0 15 10 ? \* 6L | 10:15 AM on the last Friday of every month |
0 0 12 1/5 \* ? | 12 PM (noon) every 5 days every month, starting on the first day of the month |
Cron expressions have six required fields and one optional field separated by white space.
| Field | Values |
|---|---|
| Seconds | 0-59 |
| Minutes | 0-59 |
| Hours | 0-23 |
| Day-of-month | 1-31 |
| Month | 1-12, JAN-DEC |
| Day-of-Week | 1-7, SUN-SAT |
| Year (Optional) | <empty>, 1970-2099 |
NOTE: Non-standard schedules for cron expressions are not supported; for example, it is not possible to set a cron job to run every two weeks, as there is not field specific to weeks in a cron expression. However, it is possible to set up a variant that runs closely to two week increments. For example, using the following cron expression will run the cron job the 1st and 15th of every month at 1:30AM: 30 1 1,15 * *
Additionally, the cron expressions take wildcards as values. The frequently used ones are listed in the following table:
| Wildcard | Description |
|---|---|
* | All values. For example, when used in the minute field means "every minute". |
? | Used in day-of-month and day-of-week fields to specify "no specific value". This is useful when you need to specify something in one of the two fields, but not the other. |
- | Specify range of values. For example, 10-12 in the hour field means "from 10 to 12". |
, | Specify additional values. For example, MON,WED,FRI in the day-of-week field means the days Monday, Wednesday, and Friday. |
/ | Specify increments. For example, 0/15 in the seconds field means the 0, 15, 30, and 45 second marks of each minute. |
You can use a tool like crontab guru or cronmaker to generate cron expressions.