The best way I found to run WebJob is to use a scheduled WebJob for the job queue, which must be done using the built-in queue, and then create a separate WebJob that runs continuously, which runs every time a new queue message appears, set BatchSize = 1. This effectively prevents the execution of any task at the same time.
Here is an example of code in WebJob that queues a message.
class Program { static void Main() { var host = new JobHost(); host.Call(typeof(Functions).GetMethod("QueueSomething")); } } public class Functions { [NoAutomaticTrigger] public static void QueueSomething([Queue("myqueue")] ICollector<string> message, TextWriter log) { //do some work here to create a message to pass to the other WebJob so it can execute your task string x = "serialize some data or instructions to pass"; //if I want to pass it a couple of things to do use ICollector above and add this to the queue too string x2 = "some additional task to do"; //Add the json to the WebJobs queue message.Add(x); message.Add(x2); }
Here is the code in a constantly running WebJob. This controls "myqueue" and then calls DoSomething () when a new message appears. The main BatchSize property that prevents this WebJob from reading and processing another message until the first is complete.
class Program { static void Main() { JobHostConfiguration config = new JobHostConfiguration(); //Read and process one message at a time config.Queues.BatchSize = 1; var host = new JobHost(config); host.RunAndBlock(); } } public class Functions { public static void DoSomething([QueueTrigger("myqueue")] string message, TextWriter log) { //Read and deserialize your message and then do some work with it string d = JsonConvert.DeserializeObject(message); } }
Hope this helps.
source share