@feige0629/web-worker-pools
TypeScript icon, indicating that this package has built-in type declarations

0.1.15 • Public • Published

简介

web-worker-pools 为 worker 创建线程池

1、使用

主线程代码

import Worker from './worker?worker';
import { webWorkerPools } from '@feige0629/web-worker-pools';
export interface ParamsType {
    name:string;
}
export type ResultType = string;

const workerPools = new webWorkerPools<ParamsType, ResultType>({
  "debug": true,  //是否开启debug
  "processName": 'testFunc', // 进程名称
  "closeWorkerTime":60000,  // 检查空闲 Worker 是否需要关闭(60秒)
  "checkIdleInterval":60000  // 定时器间隔,用于检查空闲 Worker 是否需要关闭(60秒)
}, ()=>new Worker());

export const testFunc = async (params:ParamsType):Promise<ResultType> => {
    return workerPools.workerManager(params, 'task1');
}

// 调用自动销毁
workerPools.autoCloseWorker(['task1']);// ['task1']为保留任务不超时销毁

worker线程代码

import type { WorkerParams } from '@feige0629/web-worker-pools';
import type { ResultType, ParamsType } from './';
import { handleMessage, handleError } from '@feige0629/web-worker-pools';

function getResult(params:WorkerParams<ParamsType>): ResultType {
  // 业务代码

  return params.name; //测试返回name
}

// 监听消息
self.addEventListener("message", async (event: MessageEvent) => {
  const params:WorkerParams<ParamsType> = event.data?.params;
  handleMessage<ParamsType, ResultType>(event, ()=> getResult(params))
}, false)

// 错误提示
self.addEventListener("error", handleError, false);

业务中使用

import React, { useEffect, useState } from "react";
import { testFunc } from './index';

export function App(){
  const [name, setName] = useState<string>('');
  
  useEffect(()=>{
    testFunc('飞哥')
    .then((result:string)=>{
      setName(result);
    })
  },[])

  return <div>{name}</div>
}

Readme

Keywords

none

Package Sidebar

Install

npm i @feige0629/web-worker-pools

Weekly Downloads

6

Version

0.1.15

License

ISC

Unpacked Size

81.4 kB

Total Files

13

Last publish

Collaborators

  • tangfei0629