Try to submit a job without waiting for a worker to become available Returns None if no workers are available, otherwise returns a JobHandle.
(&self, job: T)
| 94 | /// |
| 95 | /// Returns None if no workers are available, otherwise returns a JobHandle. |
| 96 | pub async fn try_submit(&self, job: T) -> Result<Option<JobHandle>, JobError> { |
| 97 | // Check if we're shutting down |
| 98 | if *self.shutting_down.lock().await { |
| 99 | return Err(JobError::from("Worker pool is shutting down".to_string())); |
| 100 | } |
| 101 | |
| 102 | // Try to acquire a permit without waiting |
| 103 | let permit = match self.semaphore.clone().try_acquire_owned() { |
| 104 | Ok(permit) => permit, |
| 105 | Err(_) => return Ok(None), |
| 106 | }; |
| 107 | |
| 108 | // Get the job ID before moving the job |
| 109 | let job_id = job.job_id(); |
| 110 | |
| 111 | // Add the job to the active jobs set for tracking |
| 112 | let mut jobs = self.active_jobs.lock().await; |
| 113 | jobs.spawn(async move { |
| 114 | // Hold the permit for the duration of the job |
| 115 | let _permit = permit; |
| 116 | |
| 117 | // Execute the job |
| 118 | job.execute().await |
| 119 | }); |
| 120 | drop(jobs); |
| 121 | |
| 122 | Ok(Some(JobHandle { job_id })) |
| 123 | } |
| 124 | |
| 125 | /// Clean up completed jobs from the internal tracking |
| 126 | /// |