Last active
May 31, 2024 16:47
-
-
Save Artaud/141332b8d0967564244fa5c7a356e7e5 to your computer and use it in GitHub Desktop.
Basic worker thread pool in Feathers, using threads.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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