I am about to start a C# .NET 4.0 project that creates a job scheduler.
- The job has no due date, and are potentially long running, up to days.
- The job has 3 priorities: idle, normal, critical; from lowest to highest.
- New job(s) are continuously being created.
- Newer job with higher priority should take precedence over lower priority job even if the old job has been created for a long time.
- Each job will be handled by single long running thread.
- Job are re-entrant. The state of job is persisted to the database, so it is okay to pause the job or terminate the job thread at anytime.
My plan is to use a semaphore, and set the number of concurrent entries to the number of system cores. A new thread will be created for every jobs in queue, and all thread will be blocked by the semaphore in the beginning.
My problem is to guarantee high priority thread will enter the semaphore first when semaphore calls release() method. Doable?
My second problem is to have a thread that is inside the semaphore to exit when higher priority job thread come to existence and have the exiting job thread go back to the thread queue to wait for the semaphore. Doable?
For those two problems, is semaphore the right approaches? If not what do you suggest?
Well, I would lean more towards something like the following…
First, Start all the threads you want:
You will need an interface to describe the priority of a task
Then create a Queue management object. This would obviously get more complicated as it may need to sync with your database, etc…
And Lastly create your worker thread something like the following: