0.1.10 • Published 5 months ago

@feige0629/web-worker-pools v0.1.10

Weekly downloads
-
License
ISC
Repository
-
Last release
5 months ago

简介

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>
}
0.1.10

5 months ago

0.1.9

6 months ago

0.1.8

7 months ago

0.1.7

8 months ago

0.1.6

8 months ago

0.1.5

8 months ago

0.1.4

8 months ago

0.1.3

8 months ago

0.1.2

8 months ago

0.1.1

8 months ago

0.1.0

8 months ago