7

我正在尝试通过控制台应用程序(.Net Framework 4.5.2)熟悉 C# FluentScheduler 库。以下是已编写的代码:

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();


    }
}

此代码执行没有任何错误,但我没有看到控制台上写的任何内容。我在这里错过了什么吗?

4

2 回答 2

11

您以错误的方式使用该库 - 您不应该创建一个新的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();
}
于 2017-03-23T16:39:00.263 回答
10

FluentScheduler 是一个很棒的包,但我会避免尝试在评论中建议的 ASP.Net 应用程序中使用它 - 当您的应用程序在一段时间不活动后卸载时,您的调度程序会有效停止。

一个更好的主意是将其托管在专用的 Windows 服务中。

除此之外 - 你已经要求一个控制台应用程序实现,所以试试这个:

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);
        }
    }
}
于 2017-03-23T16:38:26.693 回答