2017-03-23 23 views
1

我正在嘗試通過一個控制檯應用程序(.NET框架4.5.2)熟悉C#FluentScheduler庫。下面是寫的代碼:如何使用FluentScheduler庫在C#中計劃任務?

class Program 
{ 
    static void Main(string[] args) 
    { 
     JobManager.Initialize(new MyRegistry()); 
    } 
} 


public class MyRegistry : Registry 
{ 
    public MyRegistry() 
    { 
     Action someMethod = new Action(() => 
     { 
      Console.WriteLine("Timed Task - Will run now"); 
     }); 

     Schedule schedule = new Schedule(someMethod); 

     schedule.ToRunNow(); 


    } 
} 

此代碼執行沒有任何錯誤,但我沒有看到寫在控制檯上的任何東西。我在這裏錯過了什麼嗎?

+0

你應該已經運行ASP.NET的服務調度作業 –

+0

@MaksimSimkin感謝您的答覆。你的意思是我需要創建一個Windows服務?我的印象是,使用Fluent Scheduler我們不需要Windows服務。 – Ketan

+0

您應該創建一個asp.net項目,並將其駐留,例如在你的IIS,看這裏:https://github.com/fluentscheduler/FluentScheduler#using-it-with-aspnet –

回答

2

您正在使用庫中的錯誤的方式 - 你不應該創建一個新的Schedule
您應該使用的是Registry內的方法。

public class MyRegistry : Registry 
{ 
    public MyRegistry() 
    { 
     Action someMethod = new Action(() => 
     { 
      Console.WriteLine("Timed Task - Will run now"); 
     }); 

     // Schedule schedule = new Schedule(someMethod); 
     // schedule.ToRunNow(); 

     this.Schedule(someMethod).ToRunNow(); 
    } 
} 

的第二個問題是,控制檯應用程序將立即退出初始化之後,所以加一個Console.ReadLine()

static void Main(string[] args) 
{ 
    JobManager.Initialize(new MyRegistry()); 
    Console.ReadLine(); 
} 
1

FluentScheduler是一個很大的包,但我儘量嘗試使用它在一個ASP.Net應用程序作爲評論建議 - 當你的應用程序在停用一段時間的調度有效地停止後卸載。

一個更好的主意是舉辦它在一個專用的窗口服務。

這一邊 - 你問一個控制檯應用程序實現,所以這給一試:

using System; 
using FluentScheduler; 

namespace SchedulerDemo 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      // Start the scheduler 
      JobManager.Initialize(new ScheduledJobRegistry()); 

      // Wait for something 
      Console.WriteLine("Press enter to terminate..."); 
      Console.ReadLine(); 

      // Stop the scheduler 
      JobManager.StopAndBlock(); 
     } 
    } 

    public class ScheduledJobRegistry : Registry 
    { 
     public ScheduledJobRegistry() 
     { 
      Schedule<MyJob>() 
        .NonReentrant() // Only one instance of the job can run at a time 
        .ToRunOnceAt(DateTime.Now.AddSeconds(3)) // Delay startup for a while 
        .AndEvery(2).Seconds();  // Interval 

      // TODO... Add more schedules here 
     } 
    } 

    public class MyJob : IJob 
    { 
     public void Execute() 
     { 
      // Execute your scheduled task here 
      Console.WriteLine("The time is {0:HH:mm:ss}", DateTime.Now); 
     } 
    } 
} 
+0

這個代碼工作太多,但看起來你可以標記只有一個正確答案:(,感謝您的答覆。 – Ketan

+0

執行不獲取調用,也UPI知道它可能是什麼? – coder771

相關問題