Skip to content

Scheduling

Bunstone supports decorator-based scheduling for background tasks.

@Timeout()

Executes a method once after a specified delay (in milliseconds).

typescript
@Injectable()
export class TaskService {
  @Timeout(5000)
  runOnce() {
    console.log("Executed after 5 seconds");
  }
}

@Cron()

Executes a method repeatedly based on a cron expression.

typescript
import { Cron } from "@grupodiariodaregiao/bunstone";

@Injectable()
export class CleanupService {
  @Cron("0 0 * * *") // Every day at midnight
  handleCleanup() {
    console.log("Cleaning up database...");
  }
}

Note: Scheduling decorators work on any @Injectable class that is registered as a provider in a @Module.

Practical Example

Explore more scheduling options and configurations:

ts
import { Module, Injectable, Cron, Timeout, AppStartup } from "../../index";

@Injectable()
class NotificationTask {
  @Cron("*/10 * * * * *") // Every 10 seconds
  handleCron() {
    console.log("[Schedule] Running periodic notification check...");
  }

  @Timeout(5000) // 5 seconds after startup
  handleTimeout() {
    console.log("[Schedule] App has been running for 5 seconds!");
  }
}

@Module({
  providers: [NotificationTask],
})
class AppModule {}

const app = AppStartup.create(AppModule);
app.listen(3000, () => {
  console.log("Scheduling example is running on http://localhost:3000");
});

See it on GitHub

Released under the MIT License.