

Also from Kynth Studios


Also from Kynth Studios


Also from Kynth Studios
12345# 任务与队列(Task)67## 内置任务(代码中配置)89内置定时任务能力来自于[midwayjs](https://www.midwayjs.org/docs/extensions/cron)1011### 引入组件1213```ts14import { Configuration } from "@midwayjs/core";15import * as cron from "@midwayjs/cron"; // 导入模块16import { join } from "path";1718@Configuration({19 imports: [cron],20 importConfigs: [join(__dirname, "config")],21})22export class AutoConfiguration {}23```2425### 使用2627```ts28import { Job, IJob } from "@midwayjs/cron";29import { FORMAT } from "@midwayjs/core";3031@Job({32 cronTime: FORMAT.CRONTAB.EVERY_PER_30_MINUTE,33 start: true,34})35export class DataSyncCheckerJob implements IJob {36 async onTick() {37 // ...38 }39}40```4142```ts43@Job("syncJob", {44 cronTime: "*/2 * * * * *", // 每隔 2s 执行45})46export class DataSyncCheckerJob implements IJob {47 async onTick() {48 // ...49 }50}51```5253### 规则 cron5455```ts56* * * * * *57┬ ┬ ┬ ┬ ┬ ┬58│ │ │ │ │ |59│ │ │ │ │ └ day of week (0 - 7) (0 or 7 is Sun)60│ │ │ │ └───── month (1 - 12)61│ │ │ └────────── day of month (1 - 31)62│ │ └─────────────── hour (0 - 23)63│ └──────────────────── minute (0 - 59)64└───────────────────────── second (0 - 59, optional)6566```6768::: warning 警告6970注意:该方式在多实例部署的情况下无法做到任务之前的协同,任务存在重复执行的可能7172:::7374## 本地任务(管理后台配置,v8.0 新增)7576可以到登录后台`/系统管理/任务管理/任务列表`,配置任务。默认是不需要任何依赖的, 旧版需要依赖`redis`才能使用该功能。7778### 配置任务7980配置完任务可以调用你配置的 service 方法,如:taskDemoService.test()8182### 规则 cron8384规则 cron8586```ts87* * * * * *88┬ ┬ ┬ ┬ ┬ ┬89│ │ │ │ │ |90│ │ │ │ │ └ day of week (0 - 7) (0 or 7 is Sun)91│ │ │ │ └───── month (1 - 12)92│ │ │ └────────── day of month (1 - 31)93│ │ └─────────────── hour (0 - 23)94│ └──────────────────── minute (0 - 59)95└───────────────────────── second (0 - 59, optional)9697```9899规则示例:100101- 每 5 秒执行一次: `*/5 * * * * *`102- 每 5 分钟执行一次: `*/5 * * * *`103- 每小时执行一次: `0 * * * *`104- 每天执行一次: `0 0 * * *`105- 每天 1 点执行: `0 1 * * *`106- 每周执行一次: `0 0 * * 0`107- 每月执行一次: `0 0 1 * *`108109110111## 分布式任务(管理后台配置)112113当需要分布式部署时,需要开启分布式任务,通过 redis 作为协同整个集群的任务,防止任务重复执行等异常情况。114115#### 引入插件116117`src/configuration.ts`118119```ts120import { Configuration, App } from "@midwayjs/core";121import { join } from "path";122import * as task from "@cool-midway/task";123124@Configuration({125 imports: [task],126 importConfigs: [join(__dirname, "./config")],127})128export class ContainerLifeCycle {129 @App()130 app: koa.Application;131132 async onReady() {}133}134```135136#### 配置137138[redis>=5.x](https://redis.io/),推荐[redis>=7.x](https://redis.io/)139140`src/config/config.default.ts`141142::: warning 注意143很多人忽略了这个配置,导致项目包 redis 连接错误!!!144:::145146```ts147import { CoolFileConfig, MODETYPE } from "@cool-midway/file";148import { MidwayConfig } from "@midwayjs/core";149import * as fsStore from "cache-manager-fs-hash";150151export default {152 // 修改成你自己独有的key153 keys: "cool-admin for node",154 koa: {155 port: 8001,156 },157 // cool配置158 cool: {159 redis: {160 host: "127.0.0.1",161 port: 6379,162 password: "",163 db: 0,164 },165 },166} as unknown as MidwayConfig;167```168169redis cluster 方式170171```ts172[173 {174 host: "192.168.0.103",175 port: 7000,176 },177 {178 host: "192.168.0.103",179 port: 7001,180 },181 {182 host: "192.168.0.103",183 port: 7002,184 },185 {186 host: "192.168.0.103",187 port: 7003,188 },189 {190 host: "192.168.0.103",191 port: 7004,192 },193 {194 host: "192.168.0.103",195 port: 7005,196 },197];198```199200### 创建执行任务的 service201202```ts203import { Provide } from "@midwayjs/core";204import { BaseService } from "@cool-midway/core";205/**206 * 任务执行的demo示例207 */208@Provide()209export class DemoTaskService extends BaseService {210 /**211 * 测试任务执行212 * @param params 接收的参数 数组 [] 可不传213 */214 async test(params?: []) {215 // 需要登录后台任务管理配置任务216 console.log("任务执行了", params);217 }218}219```220221### 配置定时任务222223登录后台 任务管理/任务列表224225226227::: warning228截图中的 demoTaskService 为上一步执行任务的 service 的实例 ID,midwayjs 默认为类名首字母小写!!!229230任务调度基于 redis,所有的任务都需要通过代码去维护任务的创建,启动,暂停。 所以直接改变数据库的任务状态是无效的,redis 中的信息还未清空, 任务将继续执行。231:::232233## 队列234235之前的分布式任务调度,其实是利用了[bullmq](https://docs.bullmq.io/)的重复队列机制。236237在项目开发过程中特别是较大型、数据量较大、业务较复杂的场景下往往需要用到队列。 如:抢购、批量发送消息、分布式事务、订单 2 小时后失效等。238239得益于[bullmq](https://docs.bullmq.io/),cool 的队列也支持`延迟`、`重复`、`优先级`等高级特性。240241### 创建队列242243一般放在名称为 queue 文件夹下244245#### 普通队列246247普通队列数据由消费者自动消费,必须重写 data 方法用于被动消费数据。248249`src/modules/demo/queue/comm.ts`250251```ts252import { BaseCoolQueue, CoolQueue } from "@cool-midway/task";253import { IMidwayApplication } from "@midwayjs/core";254import { App } from "@midwayjs/core";255256/**257 * 普通队列258 */259@CoolQueue()260export class DemoCommQueue extends BaseCoolQueue {261 @App()262 app: IMidwayApplication;263264 async data(job: any, done: any): Promise<void> {265 // 这边可以执行定时任务具体的业务或队列的业务266 console.log("数据", job.data);267 // 抛出错误 可以让队列重试,默认重试5次268 //throw new Error('错误');269 done();270 }271}272```273274#### 主动队列275276主动队列数据由消费者主动消费277278`src/modules/demo/queue/getter.ts`279280```ts281import { BaseCoolQueue, CoolQueue } from "@cool-midway/task";282283/**284 * 主动消费队列285 */286@CoolQueue({ type: "getter" })287export class DemoGetterQueue extends BaseCoolQueue {}288```289290主动消费数据291292```ts293 // 主动消费队列294 @Inject()295 demoGetterQueue: DemoGetterQueue;296297 const job = await this.demoGetterQueue.getters.getJobs(['wait'], 0, 0, true);298 // 获得完将数据从队列移除299 await job[0].remove();300```301302### 发送数据303304```ts305import { Get, Inject, Post, Provide } from "@midwayjs/core";306import { CoolController, BaseController } from "@cool-midway/core";307import { DemoCommQueue } from "../../queue/comm";308import { DemoGetterQueue } from "../../queue/getter";309310/**311 * 队列312 */313@Provide()314@CoolController()315export class DemoQueueController extends BaseController {316 // 普通队列317 @Inject()318 demoCommQueue: DemoCommQueue;319320 // 主动消费队列321 @Inject()322 demoGetterQueue: DemoGetterQueue;323324 /**325 * 发送数据到队列326 */327 @Post("/add", { summary: "发送队列数据" })328 async queue() {329 this.demoCommQueue.add({ a: 2 });330 return this.ok();331 }332333 /**334 * 获得队列中的数据,只有当队列类型为getter时有效335 */336 @Get("/getter")337 async getter() {338 const job = await this.demoCommQueue.getters.getJobs(["wait"], 0, 0, true);339 // 获得完将数据从队列移除340 await job[0].remove();341 return this.ok(job[0].data);342 }343}344```345346队列配置347348```ts349interface JobOpts {350 priority: number; // Optional priority value. ranges from 1 (highest priority) to MAX_INT (lowest priority). Note that351 // using priorities has a slight impact on performance, so do not use it if not required.352353 delay: number; // An amount of milliseconds to wait until this job can be processed. Note that for accurate delays, both354 // server and clients should have their clocks synchronized. [optional].355356 attempts: number; // The total number of attempts to try the job until it completes.357358 repeat: RepeatOpts; // Repeat job according to a cron specification.359360 backoff: number | BackoffOpts; // Backoff setting for automatic retries if the job fails, default strategy: `fixed`361362 lifo: boolean; // if true, adds the job to the right of the queue instead of the left (default false)363 timeout: number; // The number of milliseconds after which the job should be fail with a timeout error [optional]364365 jobId: number | string; // Override the job ID - by default, the job ID is a unique366 // integer, but you can use this setting to override it.367 // If you use this option, it is up to you to ensure the368 // jobId is unique. If you attempt to add a job with an id that369 // already exists, it will not be added.370371 removeOnComplete: boolean | number; // If true, removes the job when it successfully372 // completes. A number specified the amount of jobs to keep. Default behavior is to keep the job in the completed set.373374 removeOnFail: boolean | number; // If true, removes the job when it fails after all attempts. A number specified the amount of jobs to keep375 // Default behavior is to keep the job in the failed set.376 stackTraceLimit: number; // Limits the amount of stack trace lines that will be recorded in the stacktrace.377}378```379380::: tip381this.demoQueue.queue 获得的就是 bull 实例,更多 bull 的高级用户可以查看[bull 文档](https://github.com/OptimalBits/bull/blob/develop/REFERENCE.md)382:::383
One repository carrying more than one format is the comparison this product exists for: does anyone actually write different content in each file, or is one a copy of the other?
| Repository | Format | Stack | Covers | Score | Changed |
|---|---|---|---|---|---|
| cool-team-official/cool-admin-midway.cursor/rules/authority.mdc · 3.3k | Cursor rules | security | 54/100 | today | |
| cool-team-official/cool-admin-midway.cursor/rules/cache.mdc · 3.3k | Cursor rules | no sections | 58/100 | today | |
| cool-team-official/cool-admin-midway.cursor/rules/controller.mdc · 3.3k | Cursor rules | api | 46/100 | today | |
| cool-team-official/cool-admin-midway.cursor/rules/db.mdc · 3.3k | Cursor rules | setupdatabase | 62/100 | today | |
| cool-team-official/cool-admin-midway.cursor/rules/event.mdc · 3.3k | Cursor rules | no sections | 45/100 | today | |
| cool-team-official/cool-admin-midway.cursor/rules/module.mdc · 3.3k | Cursor rules | no sections | 50/100 | today | |
| cool-team-official/cool-admin-midway.cursor/rules/service.mdc · 3.3k | Cursor rules | database | 54/100 | today | |
| cool-team-official/cool-admin-midway.cursor/rules/socket.mdc · 3.3k | Cursor rules | no sections | 58/100 | today | |
| cool-team-official/cool-admin-midway.cursor/rules/tenant.mdc · 3.3k | Cursor rules | no sections | 50/100 | today | |
| cool-team-official/cool-admin-midway.cursorrules · 3.3k | .cursorrules | no sections | 39/100 | today |
Same format, overlapping stack, ranked by quality.
| Repository | Format | Stack | Covers | Score | Changed |
|---|---|---|---|---|---|
| hiromaily/go-crypto-wallet.cursor/rules/typescript.mdc · 126 | Cursor rules | setupbuildtestlint-format+6 | 100/100 | 14 days ago | |
| TechSquidTV/Hermes.cursor/rules/10-hermes-api.mdc · 46 | Cursor rules | testlint-formatstylearch+5 | 100/100 | 14 days ago | |
| Allymahmoud/case-intake-platform.cursor/rules/frontend.mdc · 0 | Cursor rules | setuptestlint-formatstyle+7 | 99/100 | 14 days ago | |
| deifos/clipmira-subtitles.cursor/rules/frontend.mdc · 1 | Cursor rules | setuptestlint-formatstyle+7 | 99/100 | 14 days ago | |
| markstev/mark-starter.cursor/rules/frontend.mdc · 0 | Cursor rules | setuptestlint-formatstyle+6 | 99/100 | 14 days ago | |
| dodgecfr/combatfilms-webapp.cursor/rules/frontend.mdc · 0 | Cursor rules | setuptestlint-formatstyle+7 | 99/100 | 14 days ago | |
| langflow-ai/langflow.cursor/rules/docs_development.mdc · 153k | Cursor rules | setupbuildtestlint-format+7 | 97/100 | 14 days ago | |
| TechSquidTV/Hermes.cursor/rules/20-hermes-api-tests.mdc · 46 | Cursor rules | teststyletesting-strategysecurity+3 | 97/100 | 14 days ago |
A badge carrying the measured quality of the strongest agent config file in this repository, out of 100. It reads from this index every time somebody loads your page, so it changes when the measurement changes and there is nothing to keep up to date. Free, no account, and the value is not something you or we can set by hand.
[](https://rulestack.kynth.studio/configs/cool-team-official-cool-admin-midway-cursor-rules-task)Would rather not hotlink us? Every badge is also served in shields.io’s endpoint schema, so shields renders the image and your readers never talk to our domain:
Published by Toolproof, the masthead over this index and eight others. The method behind the number is at toolproof.kynth.studio/methodology, and the whole thing is readable as JSON with no key at /api.