Concepts: Tasks (Core)
Tasks are like crons, but better... yeah okay, that is questionable. But they are definitely crons, kinda.
Introduction
Tasks are used to run code at specific times... you guessed it! Like crons, we even use the same cron syntax, so there is that. Essentially, tasks are mostly built for being able to schedule potentially clean up jobs, or other things that need to be scheduled, but not something that fits into another category, and the process runs within the same process as the main application, now this is good... and bad, but don't worry, we thought about this. You can use Workers to run tasks in a separate thread, so you'll be alright.
Another cool thing about tasks is that they can be run manually, or be defined as a task that can ONLY be ran manually, you see some tasks, maybe a database clean up, or maybe to send out a newsletter, you don't want that to run on a schedule (or maybe you do) but either way, you can define tasks to be run manually, or on a schedule, or both. You can call them using the TasksProvider
which can be used to get information about tasks and run them manually.
Now we haven't touched on this just yet, but to give you a hint, we also have a Scripts - which can be called from our CLI package to run within the same process as the main application, so you can actually call tasks from scripts, pretty cool right? You may ask... and I fully understand why you would ask, why would I not just write the code within the script? Well, you could, but what if you wanted to run the same code on a schedule, maybe manually via a script, and maybe even via an API endpoint? Technically you could use a provider, you could also just use a simple class, but... yeah, no argument there, many ways to do the same thing - we just wanted to give you options really.
Creating tasks
I won't say it again, don't worry... it's simple!
Manual task
import { BaseTask, Task } from '@sodacore/core';
@Task(undefined, { name: 'Test 1' })
export default class TestTask extends BaseTask {
public async run() {
console.log('Test task ran!');
}
}
Scheduled task
Note: This task can still be ran manually.
import { BaseTask, Task } from '@sodacore/core';
@Task('*/5 * * * *', { name: 'Test 1' })
export default class TestTask extends BaseTask {
public async run() {
console.log('Test task ran!');
}
}