2009-08-31 15 views

risposta

74

Hai un paio di opzioni, a seconda di cosa vuoi fare e di come vuoi configurarlo. Ad esempio, è possibile installare un server Quartz.Net come un server Windows autonomo, che può essere incorporato anche nell'applicazione asp.net.

Se si desidera eseguire esso incorporato, è possibile avviare il server da dire la vostra global.asax, come questo (dagli esempi di codice sorgente, ad esempio # 12):

NameValueCollection properties = new NameValueCollection(); 
properties["quartz.scheduler.instanceName"] = "RemoteServer"; 

// set thread pool info 
properties["quartz.threadPool.type"] = "Quartz.Simpl.SimpleThreadPool, Quartz"; 
properties["quartz.threadPool.threadCount"] = "5"; 
properties["quartz.threadPool.threadPriority"] = "Normal"; 

ISchedulerFactory sf = new StdSchedulerFactory(properties); 
IScheduler sched = sf.GetScheduler(); 
sched.Start(); 

se lo si esegue come un servizio, si dovrebbe connettersi in remoto ad esso come questo (da esempio # 12):

NameValueCollection properties = new NameValueCollection(); 
properties["quartz.scheduler.instanceName"] = "RemoteClient"; 

// set thread pool info 
properties["quartz.threadPool.type"] = "Quartz.Simpl.SimpleThreadPool, Quartz"; 
properties["quartz.threadPool.threadCount"] = "5"; 
properties["quartz.threadPool.threadPriority"] = "Normal"; 

// set remoting expoter 
properties["quartz.scheduler.proxy"] = "true"; 
properties["quartz.scheduler.proxy.address"] = "tcp://localhost:555/QuartzScheduler"; 
// First we must get a reference to a scheduler 
ISchedulerFactory sf = new StdSchedulerFactory(properties); 
IScheduler sched = sf.GetScheduler(); 

una volta ottenuto un riferimento allo scheduler (sia tramite i servizi remoti o perché si dispone di un'istanza incorporato) è possibile pianificare lavori come questo:

// define the job and ask it to run 
JobDetail job = new JobDetail("remotelyAddedJob", "default", typeof(SimpleJob)); 
JobDataMap map = new JobDataMap(); 
map.Put("msg", "Your remotely added job has executed!"); 
job.JobDataMap = map; 
CronTrigger trigger = new CronTrigger("remotelyAddedTrigger", "default", "remotelyAddedJob", "default", DateTime.UtcNow, null, "/5 * * ? * *"); 
// schedule the job 
sched.ScheduleJob(job, trigger); 

Ecco un link ad alcuni post che ho scritto per le persone iniziare a lavorare con Quartz.Net: http://jvilalta.blogspot.com/2009/03/getting-started-with-quartznet-part-1.html

+1

Potresti aggiornare i post, ecc. Che utilizza l'ultima versione? Sembra che il formato per i valori di configurazione sia diverso ora. Grazie! – Snowy

+0

Penso che il modo più nuovo per la 2.x è: # export questo server per servizi remoti contesto quartz.scheduler.exporter.type = Quartz.Simpl.RemotingSchedulerExporter, quarzo quartz.scheduler.exporter.port = 555 quarzo. scheduler.exporter.bindName = QuartzScheduler quartz.scheduler.exporter.channelType = tcp quartz.scheduler.exporter.channelName = httpQuartz – NickG

+0

Agh. Odio come non puoi avere nuove righe nei commenti! – NickG

2

Qualche settimana fa ho scritto su come utilizzare Quartz.Net per pianificare i processi in ruoli di Windows Azure lavoratori. Da allora mi sono imbattuto in un requisito che mi ha spinto a creare un wrapper attorno a Quartz.Net IScheduler. JobSchedule ha la responsabilità di leggere una stringa di pianificazione da CloudConfigurationManager e pianificare un lavoro.

CloudConfigurationManager legge le impostazioni dal file di configurazione del ruolo, che può essere modificato tramite il portale di gestione di Windows Azure nella sezione di configurazione dei servizi cloud.

L'esempio seguente pianificherà un lavoro che deve essere eseguito ogni giorno alle 6 AM, 8 AM, 10 AM, 12:30 PM e 16:30. La pianificazione è definita nelle impostazioni del ruolo che possono essere modificate tramite Visual Studio. Per raggiungere le impostazioni del ruolo, accedere al progetto Servizio cloud di Windows Azure e individuare le configurazioni di ruolo desiderate nella cartella Ruolo. Apri l'editor di configurazione facendo doppio clic sul file di configurazione, quindi vai alla scheda "Impostazioni". Fare clic su "Aggiungi impostazioni" e denominare la nuova impostazione "JobDailySchedule" e impostarne il valore su 6: 0; 8: 0; 10: 0; 12: 30; 16: 30;

The code from this Post is part of the Brisebois.WindowsAzure NuGet Package 

To install Brisebois.WindowsAzure, run the following command in the Package Manager Console 

PM> Install-Package Brisebois.WindowsAzure 

Get more details about the Nuget Package. 

Quindi utilizzare la pianificazione di JobSchedule un lavoro giornaliero utilizzando la pianificazione definita nel file di configurazione del ruolo.

var schedule = new JobSchedule(); 

schedule.ScheduleDailyJob("JobDailySchedule", 
          typeof(DailyJob)); 

L'implementazione di DailyJob è la seguente. Poiché questa è una demo, non aggiungerò alcuna logica specifica al lavoro.

public class DailyJob : IJob 
{ 
    public void Execute(IJobExecutionContext context) 
    { 
     //Do your daily work here 
    } 
} 

JobSchedule esegue il wrapping di Quartz.Net. In un post precedente ho parlato dell'importanza del wrapping degli strumenti di terze parti, questo è un esempio eccellente perché sto contenendo la logica di pianificazione del lavoro e potrei potenzialmente modificare questa logica senza influire sul codice che utilizza JobSchedule.

JobSchedule deve essere configurato all'avvio del ruolo e l'istanza di JobSchedule deve essere mantenuta per tutta la durata del ruolo. È possibile modificare la pianificazione modificando l'impostazione "JobDailySchedule" tramite il portale di gestione di Windows Azure nella sezione di configurazione dei servizi cloud. Quindi, per applicare la nuova pianificazione, riavviare l'istanza del ruolo tramite il portale di gestione di Windows Azure nella sezione delle istanze dei servizi cloud.

public class JobSchedule 
{ 
    private readonly IScheduler sched; 

    public JobSchedule() 
    { 
     var schedFact = new StdSchedulerFactory(); 

     sched = schedFact.GetScheduler(); 
     sched.Start(); 
    } 

    /// <summary> 
    /// Will schedule jobs in Eastern Standard Time 
    /// </summary> 
    /// <param name="scheduleConfig">Setting Key from your CloudConfigurations, 
    ///        value format "hh:mm;hh:mm;"</param> 
    /// <param name="jobType">must inherit from IJob</param> 
    public void ScheduleDailyJob(string scheduleConfig, 
           Type jobType) 
    { 
     ScheduleDailyJob(scheduleConfig, 
         jobType, 
         "Eastern Standard Time"); 
    } 

    /// <param name="scheduleConfig">Setting Key from your CloudConfigurations, 
    ///        value format "hh:mm;hh:mm;"</param> 
    /// <param name="jobType">must inherit from IJob</param> 
    public void ScheduleDailyJob(string scheduleConfig, 
           Type jobType, 
           string timeZoneId) 
    { 
     var schedule = CloudConfigurationManager.GetSetting(scheduleConfig); 
     if (schedule == "-") 
      return; 

     schedule.Split(';') 
       .Where(s => !string.IsNullOrWhiteSpace(s)) 
       .ToList() 
       .ForEach(h => 
     { 
      var index = h.IndexOf(':'); 
      var hour = h.Substring(0, index); 
      var minutes = h.Substring(index + 1, h.Length - (index + 1)); 

      var job = new JobDetailImpl(jobType.Name + hour + minutes, null, 
             jobType); 

      var dh = Convert.ToInt32(hour, CultureInfo.InvariantCulture); 
      var dhm = Convert.ToInt32(minutes, CultureInfo.InvariantCulture); 
      var tz = TimeZoneInfo.FindSystemTimeZoneById(timeZoneId); 

      var cronScheduleBuilder = CronScheduleBuilder 
              .DailyAtHourAndMinute(dh, dhm) 
              .InTimeZone(tz); 
      var trigger = TriggerBuilder.Create() 
             .StartNow() 
             .WithSchedule(cronScheduleBuilder) 
             .Build(); 

      sched.ScheduleJob(job, trigger); 
     }); 
    } 

    /// <summary> 
    /// Will schedule jobs in Eastern Standard Time 
    /// </summary> 
    /// <param name="scheduleConfig">Setting Key from your CloudConfigurations, 
    ///        value format "hh:mm;hh:mm;"</param> 
    /// <param name="jobType">must inherit from IJob</param> 
    public void ScheduleWeeklyJob(string scheduleConfig, 
            Type jobType) 
    { 
     ScheduleWeeklyJob(scheduleConfig, 
          jobType, 
          "Eastern Standard Time"); 
    } 


    /// <param name="scheduleConfig">Setting Key from your CloudConfigurations, 
    ///        value format "hh:mm;hh:mm;"</param> 
    /// <param name="jobType">must inherit from IJob</param> 
    public void ScheduleWeeklyJob(string scheduleConfig, 
            Type jobType, 
            string timeZoneId) 
    { 
     var schedule = CloudConfigurationManager.GetSetting(scheduleConfig); 

     schedule.Split(';') 
       .Where(s => !string.IsNullOrWhiteSpace(s)) 
       .ToList() 
       .ForEach(h => 
     { 
      var index = h.IndexOf(':'); 
      var hour = h.Substring(0, index); 
      var minutes = h.Substring(index + 1, h.Length - (index + 1)); 

      var job = new JobDetailImpl(jobType.Name + hour + minutes, null, 
             jobType); 

      var dh = Convert.ToInt32(hour, CultureInfo.InvariantCulture); 
      var dhm = Convert.ToInt32(minutes, CultureInfo.InvariantCulture); 
      var tz = TimeZoneInfo.FindSystemTimeZoneById(timeZoneId); 
      var builder = CronScheduleBuilder 
          .WeeklyOnDayAndHourAndMinute(DayOfWeek.Monday, 
                 dh, 
                 dhm) 
          .InTimeZone(tz); 

      var trigger = TriggerBuilder.Create() 
             .StartNow() 
             .WithSchedule(builder) 
             .Build(); 

      sched.ScheduleJob(job, trigger); 
     }); 
    } 
} 
Problemi correlati