概要 †Asp.NETのWebサイトで定期的に行いたい処理を実装する方法を二点紹介します。
Timerクラス †「Global.asax」ファイルの「Application_Start」イベントに下記のような、Timerクラスを利用して実装します。 void Application_Start(object sender, EventArgs e) { System.Timers.Timer myTimer = new System.Timers.Timer(10000); myTimer.Elapsed += new System.Timers.ElapsedEventHandler(OnTimedEvent); myTimer.Interval = 10000; myTimer.Enabled = true; } private static void OnTimedEvent(object source, System.Timers.ElapsedEventArgs e) { //ここ例として、10秒毎処理を行います。 //何かの処理... } Quartz.Net ライブラリ †サイトURL: 簡単な使い方を紹介します。 (1)web.config内の設定 <configSections> <section name="quartz" type="System.Configuration.NameValueSectionHandler, System, Version=1.0.5000.0,Culture=neutral, PublicKeyToken=b77a5c561934e089"/> <sectionGroup name="common"> <section name="logging" type="Common.Logging.ConfigurationSectionHandler, Common.Logging"/> </sectionGroup> </configSections> <common> <logging> <factoryAdapter type="Common.Logging.Simple.ConsoleOutLoggerFactoryAdapter, Common.Logging"> <arg key="showLogName" value="true"/> <arg key="showDataTime" value="true"/> <arg key="level" value="DEBUG"/> <arg key="dateTimeFormat" value="HH:mm:ss:fff"/> </factoryAdapter> </logging> </common> <quartz> <add key="quartz.scheduler.instanceName" value="ExampleDefaultQuartzScheduler"/> <add key="quartz.threadPool.type" value="Quartz.Simpl.SimpleThreadPool, Quartz"/> <add key="quartz.threadPool.threadCount" value="10"/> <add key="quartz.threadPool.threadPriority" value="2"/> <add key="quartz.jobStore.misfireThreshold" value="60000"/> <add key="quartz.jobStore.type" value="Quartz.Simpl.RAMJobStore, Quartz"/> </quartz> (2)Quartz.IJobインターフェイスの実装 public class RetrieveJob : Quartz.IJob { public RetrieveJob() { // } public void Execute(Quartz.JobExecutionContext context) { //ここで定期的に行いたい処理を実装します。 } } (3)「Global.asax」ファイルでの呼び出し Webアプリケーションが起動する際に、下記のように呼び出せます。 IScheduler sched; void Application_Start(object sender, EventArgs e) { // 在应用程序启动时运行的代码 ISchedulerFactory sf = new Quartz.Impl.StdSchedulerFactory(); sched = sf.GetScheduler(); JobDetail job = new JobDetail("job1", "group1", typeof(RetrieveJob)); //定期日時のフォーマット string cronEx = "0 0 12 * * ?"; CronTrigger trigger = new CronTrigger("trigger1", "group1", "job1", "group1",cronEx ); sched.AddJob(job, true); DateTime ft = sched.ScheduleJob(trigger); sched.Start(); } QuartzのCronTriggerクラスのAPI docs: void Application_End(object sender, EventArgs e) { // 在应用程序关闭时运行的代码 if (sched != null) { sched.Shutdown(true); } } セシウム137を97.7%吸着 コメント: |