Services are used for background work in HeronJS. They are useful for recurring jobs, startup initialization, and long-running processes that should run outside the normal HTTP request and response cycle.
How services work
A service is started by the framework when the application boots. You define its behavior with the @Service() decorator and lifecycle hooks such as @OnStart() and @PreDestroy().
In general:
@OnStart()runs when the service starts.@PreDestroy()runs before the service shuts down.modecontrols when and how the service executes.
Create an interval service
Use mode: 'Interval' when the service should run repeatedly on a fixed schedule.
@Service({ mode: 'Interval', options: { interval: 1000 } })
export class HeartbeatService {
@OnStart()
start = async () => {
// logic that runs every second
};
@PreDestroy()
destroy = async () => {
// cleanup logic
};
}This mode is useful for polling, scheduled synchronization, metrics collection, or periodic cleanup tasks.
Create a daemon service
Use mode: 'Daemon' when the service should start with the application and continue running in the background.
@Service({ mode: 'Daemon' })
export class AuditService {
@OnStart()
start = async () => {
// startup logic
};
@PreDestroy()
destroy = async () => {
// cleanup logic
};
}This mode is a good fit for background workers, listeners, or any long-lived process that should remain active while the app is running.
Create an initialize service
Use mode: 'Initialize' when the service should run once during application startup.
@Service({ mode: 'Initialize' })
export class BootstrapService {
@OnStart()
start = async () => {
// one-time startup logic
};
@PreDestroy()
destroy = async () => {
// cleanup logic
};
}This is useful for tasks such as warming caches, loading configuration, seeding application state, or verifying external dependencies before the server starts accepting traffic.
Register services
To enable services, register them in the module services array.
@Module({
services: [HeartbeatService, AuditService, BootstrapService],
})
export class AppModule {}Once registered, HeronJS will initialize the services according to their configured mode when the application starts.