1
+ import { PriorityQueue , type Job } from '../src'
2
+
3
+ interface TaskData {
4
+ name : string
5
+ duration : number
6
+ importance : number
7
+ }
8
+
9
+ async function main ( ) {
10
+ console . log ( '🚀 Priority Queue Example' )
11
+
12
+ // Create a priority queue with 5 priority levels (0-4) and dynamic reordering
13
+ const taskQueue = new PriorityQueue < TaskData > ( 'tasks' , {
14
+ levels : 5 ,
15
+ defaultLevel : 1 ,
16
+ dynamicReordering : true ,
17
+ reorderInterval : 2000 ,
18
+ } )
19
+
20
+ console . log ( '✅ Queue created with 5 priority levels' )
21
+
22
+ // Add some tasks with different priorities
23
+ const tasks = [
24
+ { name : 'Low priority task 1' , duration : 500 , importance : 1 } ,
25
+ { name : 'Medium priority task' , duration : 300 , importance : 5 } ,
26
+ { name : 'High priority task' , duration : 200 , importance : 8 } ,
27
+ { name : 'Critical task' , duration : 100 , importance : 10 } ,
28
+ { name : 'Low priority task 2' , duration : 400 , importance : 2 } ,
29
+ ]
30
+
31
+ console . log ( '📝 Adding tasks with different priorities...' )
32
+
33
+ // Add tasks with priorities mapped from their importance
34
+ for ( const task of tasks ) {
35
+ // Map importance (1-10) to priority levels (0-4)
36
+ const priority = Math . min ( Math . floor ( task . importance / 2.5 ) , 4 )
37
+ await taskQueue . add ( task , { priority } )
38
+ console . log ( ` - Added "${ task . name } " with priority ${ priority } ` )
39
+ }
40
+
41
+ console . log ( '\n📊 Current job counts:' )
42
+ const counts = await taskQueue . getJobCounts ( )
43
+ console . log ( counts )
44
+
45
+ // Process tasks in order of priority
46
+ console . log ( '\n🔄 Processing tasks in priority order:' )
47
+ taskQueue . process ( 1 , async ( job : Job < TaskData > ) => {
48
+ const { name, duration } = job . data
49
+ const priority = job . opts . priority
50
+
51
+ console . log ( `⏳ Starting "${ name } " (priority: ${ priority } )` )
52
+
53
+ // Simulate processing by waiting for the duration
54
+ await new Promise ( resolve => setTimeout ( resolve , duration ) )
55
+
56
+ console . log ( `✅ Completed "${ name } " (priority: ${ priority } )` )
57
+
58
+ return { success : true , processedAt : new Date ( ) }
59
+ } )
60
+
61
+ // Let's add a new highest priority task during processing
62
+ setTimeout ( async ( ) => {
63
+ console . log ( '\n🚨 Adding emergency task with highest priority (4)!' )
64
+ await taskQueue . add (
65
+ { name : 'EMERGENCY TASK' , duration : 50 , importance : 10 } ,
66
+ { priority : 4 }
67
+ )
68
+ } , 600 )
69
+
70
+ // Wait for all jobs to complete
71
+ await new Promise ( resolve => setTimeout ( resolve , 3000 ) )
72
+
73
+ // Close the queue
74
+ await taskQueue . close ( )
75
+ console . log ( '\n👋 All tasks completed, queue closed' )
76
+ }
77
+
78
+ main ( ) . catch ( console . error )
0 commit comments