Need to switch to "self hosted" if the cloud hosted is in queue for more than 10

Hello all, I just wanted to check with you on this requirement in Azure DevOps, my pipeline is configured to build on cloud hosted, and self hosted based on a variable value in the Library (Ex, cloudHosted: true), if cloudHosted value is true it'll build on cloud hosted agents, else it'll build on self hosted.
Now, in some cases when there are too many jobs then my build sometime goes to queue and it'll be like around 20-to-30 taking around 1 hour to assign the job, in this case, I want to change the build to self hosted so that the agents ready in self hosted can take the job.
Would someone know how I can achieve this? The build should automatically switch to the self hosted or cloud hosted based on the queue number. Also, if possible it should change in the same build (example if the build number is 10 in queue, then the same build should run on self hosted cancelling build would result in build failure for 10th build).
Thanks