STAXIS

staxis js platform -> gitlab project
staxis on gitlab gitlab project 🏷️ V-0.X-Beta
We’re actively updating this manual. Content and layout may change as we refine it.

chronjobs

Official sources are open to Staxis GitLab group members: how to join and view the code.
Repository: chronjobs development
Versions: tags and releases


Description

chronjobs schedules timed jobs, internal functions, and external processes inside the Staxis runtime. It validates a six-field cron expression, creates runnable jobs, and keeps a minimal registry of active tasks. The pack label is chronjobs; its generic layer typology is scheduler. Other automation packs, such as sysrestart, consume that slot.


Read before flight

  • We suggest reviewing the supplied allowOpaqueExecution setting and project-wide import/filesystem scope. The default ./* rules refer to the Staxis project root, not the operating-system root.

  • We suggest keeping scheduled entry points small and internal, coordinating functions or APIs already owned by application layers. Restrict execution to a dedicated jobs directory when project-wide maintenance access is unnecessary.

  • We suggest choosing the execution boundary deliberately. An internal function shares the Staxis event loop and memory; a child process has its own runtime but still requires explicit input, output, and shutdown handling.

  • We suggest stopping owned jobs through the scheduler API before deactivating the layer. Clearing a schedule prevents future runs; it cannot safely interrupt an internal function already executing.


Files Map

File Purpose
manifest.json Declares the chronjobs label, scheduler typology, and permitted consumers
configs.js Supplies the default timezone, execution capability, script scope, and launch floor
main.js Validates job definitions and exposes the scheduler API
chronjobs.js Scheduler core, registry, message emitter, process runners, and stop logic
README.md Original setup, execution models, and usage reference

Requirements and Installation

The pack requires the Staxis Core and no additional npm scheduler library. Scheduled scripts must exist inside the project and remain within the configured access rules. Install through the Manager:

                manager -> install -> chronjobs
            

Place chronjobs before its consumers. Prepare the normal Vault and integrity material as described in First setup. Because the runtime typology is scheduler, its typology key is KEY:SCHEDULER; chronjobs remains the pack label used for Vault access requests.


Configuration

In config.js, the default timezone belongs to config.engineopt.syszone, execution and launch settings belong to config.serveropt.chronjobs, and script access rules belong to config.engineopt.guard. Merge the supplied defaults below, preserving other packs' rules:

                // config.js -> config (merge into the exported object)
                engineopt: {
                    syszone: 'Europe/Rome',
                    guard: {
                        allowOpaqueExecution: true,
                        allowedImports: [{ pack: 'chronjobs', files: ['./*'] }],
                        allowedFileAccess: [{ pack: 'chronjobs', roots: ['./*'] }]
                    }
                },
                serveropt: {
                    chronjobs: {
                        external: false,
                        minimumIntervalMs: 5000
                    }
                }
            

External processes are disabled by default. Enable config.serveropt.chronjobs.external only when the project intentionally schedules directly executable files. minimumIntervalMs defaults to 5000 and is always clamped to at least 5000 milliseconds, even if the cron expression matches every second. Sub-second repetition belongs inside the scheduled program, not in chronjobs.

The global timezone and per-job zone are validated with Node.js Intl. Use an IANA identifier supported by the installed Node.js/ICU runtime, such as Europe/Rome, or GMT. An invalid zone prevents scheduling. An omitted or empty per-job zone falls back to config.engineopt.syszone, then GMT.


Script Scope and Security

Script paths must begin with ./ or ~/, stay inside the project root, and pass through the Core's access gates. The default ./* import and filesystem rules deliberately allow compatible scripts across the project. For a restricted deployment, replace both chronjobs rules with a dedicated directory:

                // config.js -> config (replace the chronjobs rules inside these arrays)
                engineopt: {
                    guard: {
                        allowedImports: [{
                            pack: 'chronjobs',
                            files: ['./system-jobs', './system-jobs/*']
                        }],
                        allowedFileAccess: [{
                            pack: 'chronjobs',
                            roots: ['./system-jobs', './system-jobs/*']
                        }]
                    }
                }
            

Prefer small maintenance entry points inside chronjobs or a dedicated jobs directory. A job should coordinate an already authorized application function or API rather than become an independent subsystem. Project-wide access remains available when maintenance genuinely needs scripts from multiple layers. Changing allowedImports without the corresponding allowedFileAccess rule is not the complete scope change.


Execution Models

The three job types define different execution boundaries:

Type Target Runtime boundary Input Output
internal-function JavaScript module exporting a function Main Staxis process Function argument Return value / job events
internal-process Complete JavaScript program Dedicated Node.js child process Node IPC message IPC messages / exit status
external-process Directly executable project file Independent operating-system process JSON through stdin stdout, stderr, and exit status

internal-function

The scheduler imports the module through engine.importing, resolves an export matching the filename or the default export, and calls it in the main Staxis process. It suits small, trusted asynchronous application work. Arguments and results are direct and there is no child-process startup cost.

Synchronous work blocks Staxis; CPU and memory use affect the main server. A fatal failure has the smallest isolation boundary. Being inside the project does not automatically supply engine, layers, or other equipment to the function. Pass only what its entry-point contract needs.

internal-process

The scheduler uses fork to execute the entire JavaScript file as a program; it does not call one of its exports. Initial parameters arrive through Node IPC. This gives the task a separate event loop and memory space, with progress and results available through process.send.

The costs are process and memory overhead, no direct access to the parent's in-memory layer APIs, and an explicit IPC lifecycle. Handle startup, disconnect, and exit; a process can fail or be terminated without directly stopping the main Staxis process.

external-process

The scheduler uses asynchronous execFile without an implicit shell. The target remains a project file subject to Guardian roots; external refers to execution outside the Node.js/Staxis contract. It can be a directly executable script or compiled program, receiving JSON through stdin and reporting through stdout, stderr, and its exit status.

This boundary is language-independent but requires a compatible executable, permissions, and any necessary runtime or shebang. It has no Node IPC or direct layer API access. Choose the narrowest boundary that fits: internal-function for small trusted work, internal-process for isolated Node.js programs, and external-process for tasks that need another runtime or operating-system tool.


Authorize a Calling Layer

The supplied chronjobs manifest permits chronjobs and sysrestart. To add your consumer, merge its manifest.label into the permits array:

                {
                    "permits": ["chronjobs", "sysrestart", "someOtherLayer"]
                }
            

Inside someOtherLayer, use its engine and layers equipment. The Vault target is the pack label chronjobs; the requested runtime slot is scheduler. The consumer may declare "require": ["chronjobs"].

                const tokenAccess = engine.vault.requireAccess(
                    'someOtherLayer', // Requesting pack's manifest.label
                    'chronjobs'       // Provider pack's manifest.label
                )
                
                if (typeof tokenAccess !== 'string' || tokenAccess.startsWith('error:')) {
                    throw new Error('Scheduler layer access was denied')
                }
                
                const instance = layers.require(
                    'scheduler', // Provider's manifest.typology: its runtime slot
                    tokenAccess,
                    false
                )
                
                const scheduler = instance?.assets
                
                if (!scheduler || typeof scheduler.new !== 'function') {
                    throw new Error('Scheduler layer is unavailable')
                }
            

How to Use

Job creation requires an explicit unique name, a six-field cron string, a valid zone, one of the three job types, an existing project script, and optional JSON-serializable object parameters. The following small entry point and schedule follow the README's internal-function pattern. Save the module at the stated path before registering the job:

                // system-jobs/nightlyMaintenance.js
                export default async function nightlyMaintenance(params) {
                    // Coordinate your application's authorized maintenance work here.
                    return { completed: true, reason: params.reason }
                }
            
                const job = scheduler.new(
                    'nightly-maintenance',
                    '0 30 4 * * *',
                    'Europe/Rome',
                    'internal-function',
                    './system-jobs/nightlyMaintenance.js',
                    { reason: 'nightly-maintenance' }
                )
                
                if (typeof job === 'string') {
                    throw new Error(job)
                }
                
                job.on('message', message => {
                    // Receive this job's status, return values, or process messages.
                })
            

scheduler.new returns a job instance on success and a diagnostic string when initialization fails. The example checks that result before subscribing to its message channel. Its name is the control identity and is independent of the target filename, so scripts called main.js in different folders do not collide.


Six-Field Cron Format

                second minute hour day month dayOfWeek
            
Field Range
second 0..59
minute 0..59
hour 0..23
day 1..31
month 1..12
dayOfWeek 0..7; Sunday is 0 or 7
  • Wildcard: *

  • Step: */5

  • Value with step: 5/10

  • Range: 1-5

  • Range with step: 1-10/2

  • List: 1,3,5

  • Combination: 1-10/2,15,20-30/5

The full expression is validated before the timer is created. Invalid fields, ranges, and steps prevent scheduling. All fields must match the current time in the selected zone. The scheduler checks every second; the minimum launch interval and active-job checks can skip a matching tick rather than overlap the job.

Once every five minutes uses a fixed seconds field:

                0 */5 * * * *
            

By contrast, * */5 * * * * matches every second during each fifth minute. The launch floor still prevents starts closer than five seconds, but it does not change the meaning of that expression.


Registry, Messages, and Stop

scheduler.all returns a minimal snapshot such as:

                [
                    {
                        name: 'nightly-maintenance',
                        type: 'internal-function',
                        pid: null,
                        marker: 'staxis-scheduledjob:nightly-maintenance'
                    }
                ]
            

The registry does not duplicate job responses or state; these remain on the instance message channel. Use the unique name for control:

                const jobs = scheduler.all()
                
                const logged = scheduler.log('nightly-maintenance', 'manual scheduler message')
                if (typeof logged === 'string') throw new Error(logged)
                
                const stopped = await scheduler.stop('nightly-maintenance')
                if (typeof stopped === 'string') throw new Error(stopped)
            

stop clears the schedule first, then terminates an active child and removes the registry entry. A running internal function cannot be interrupted safely, but clearing its schedule prevents future runs. Stop owned jobs before layer deactivation: detach replaces the published facade and does not cancel the existing schedules. Registry control does not depend on process scanning.

Child processes receive STAXIS_SCHEDULEDJOB=staxis-scheduledjob:<name> in their environment. This marker supports operating-system and Linux CLI inspection; caller-supplied PIDs are not the control identity.


Internal Process Parameters

An internal-process receives its parameters through IPC, not command-line arguments. Access to the scheduler is authorized when the consumer obtains the API through Vault; no scheduler secret is accepted inside job parameters. The child listens once for the initial chronjob:start payload:

                // system-jobs/processMaintenance.js
                process.once('message', message => {
                    if (message?.type !== 'chronjob:start') return
                
                    const params = message.params
                
                    // Run the scheduled program with params and publish its result.
                    process.send?.({
                        type: 'chronjob:result',
                        result: { completed: true, mode: params.mode }
                    }, () => process.disconnect())
                })
            

Schedule this complete program with type='internal-process' and its project-relative path. process.send can return progress or results through the job's message emitter. The small example closes its IPC channel after publishing one result; a longer-running task must manage its own lifecycle.


External Processes

Enable external execution only for the intended project, preserving its other scheduler settings:

                // config.js -> config (merge into the exported object)
                serveropt: {
                    chronjobs: {
                        external: true
                    }
                }
            
                const externalJob = scheduler.new(
                    'daily-external-maintenance',
                    '0 0 3 * * *',
                    'Europe/Rome',
                    'external-process',
                    './system-jobs/maintenance.sh',
                    { mode: 'daily' }
                )
                
                if (typeof externalJob === 'string') {
                    throw new Error(externalJob)
                }
            

The target must already exist and be directly executable on the host. Parameters are JSON-serialized to stdin. stdout becomes the job response; a failed exit uses the process error and stderr as diagnostics. The scheduler reports script starting... while creating the process and script running... only after Node emits spawn.

On Unix-like systems, a shell script commonly needs a valid shebang and executable permission:

                #!/usr/bin/env bash
            

Python entry points have similar shebang and permission requirements. PowerShell, .cmd, and .bat files may require platform-specific hosts or command interpreters. These are possible diagnostics, not guaranteed causes: also inspect the execution flow, operating system, and target file when a run fails.


Documentation

This page is the HTML adaptation of the pack's README.md. It keeps the setup, scope, execution models, cron syntax, registry, and process-input contracts together. Complete Staxis onboarding to request GitLab access to the official sources.