Skip to content

Instantly share code, notes, and snippets.

@Artaud
Last active May 31, 2024 16:47
Show Gist options
  • Save Artaud/141332b8d0967564244fa5c7a356e7e5 to your computer and use it in GitHub Desktop.
Save Artaud/141332b8d0967564244fa5c7a356e7e5 to your computer and use it in GitHub Desktop.
Basic worker thread pool in Feathers, using threads.js
import {Id, NullableId, Paginated, Params, ServiceMethods, SetupMethod} from '@feathersjs/feathers';
import {App} from '../../app.interface'
import {isWorkerRuntime, Pool, spawn, Thread, Worker} from "threads";
import {JobWorker} from "./jobWorker";
interface ServiceOptions {}
export class Jobs implements ServiceMethods<Data>, SetupMethod {
app: App;
options: ServiceOptions;
workerPool: Pool<JobWorker & Thread> | undefined
constructor (options: ServiceOptions = {}, app: App) {
this.options = options;
this.app = app;
}
setup(app: App, path: string): void {
this.workerPool = Pool<JobWorker & Thread>(() => spawn<JobWorker>(new Worker("./jobWorker")), 8)
}
async create (data: Data, params?: Params): Promise<Data> {
const testTask = this.workerPool?.queue(jobWorker => jobWorker.doMyJob())
testTask?.then(() => {
// do something after the job finishes
})
return data;
}
}
import { expose } from "threads/worker"
const jobWorker = {
async doMyJob() {
console.log('Hello from worker thread!')
}
}
export type JobWorker = typeof jobWorker
expose(jobWorker)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment