如何通过我的应用程序设置定期任务?

时间:2014-04-10 00:33:18

标签: c# timer

我想为我的应用程序实现定期文件发布功能。例如,它每隔5分钟上传一个特定的文本文件。所以我在想某种可以处理时间的经理。我理解如何在c#中使用Timer()方法,那么如何通过我的应用程序运行来跟踪我的计时器?这种过程的适当方法是什么?

1 个答案:

答案 0 :(得分:2)

欢迎使用StackOverflow:D

我假设您正在使用Windows窗体。

以下是有关如何实现此目标的示例:

定期上传器,您可以为其设置间隔,上传处理程序并管理它(开始/停止)

上传处理程序将是您进行上传的方法,这是很好的,因为这个类不需要知道它,它只是调用它。换句话说separation of concerns

internal class MyPeriodicUploader
{
    private readonly Timer _timer;
    private Action<string, string> _uploadHandler;

    public MyPeriodicUploader(int miliseconds = 50000)
    {
        if (miliseconds <= 0) throw new ArgumentOutOfRangeException("miliseconds");
        _timer = new Timer {Interval = miliseconds};
        _timer.Tick += timer_Tick;
    }

    public string InputFile { get; set; }
    public string TargetUrl { get; set; }

    private void timer_Tick(object sender, EventArgs e)
    {
        if (_uploadHandler != null && InputFile != null && TargetUrl != null)
        {
            _uploadHandler(InputFile, TargetUrl);
        }
    }

    public void SetUploadHandler(Action<string, string> uploadHandler)
    {
        if (uploadHandler == null) throw new ArgumentNullException("uploadHandler");
        _uploadHandler = uploadHandler;
    }

    public void StartTimer()
    {
        _timer.Start();
    }

    public void StopTimer()
    {
        _timer.Stop();
    }

    public void SetUploadInterval(int minutes)
    {
        _timer.Interval = TimeSpan.FromMinutes(minutes).Milliseconds;
    }
}

现在您希望它可用于整个应用程序,打开Program.cs并在那里创建它的属性:

internal static class Program
{
    private static readonly MyPeriodicUploader _myPeriodicUploader = new MyPeriodicUploader();

    public static MyPeriodicUploader MyPeriodicUploader
    {
        get { return _myPeriodicUploader; }
    }

    /// <summary>
    ///     The main entry point for the application.
    /// </summary>
    [STAThread]
    private static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
    }
}

然后在你的表单上使用它:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        Program.MyPeriodicUploader.SetUploadHandler(UploadHandler);
        Program.MyPeriodicUploader.InputFile = "yourFileToUpload.txt";
        Program.MyPeriodicUploader.TargetUrl = "http://youraddress.com";
        Program.MyPeriodicUploader.StartTimer();
    }

    private void UploadHandler(string fileName, string targetUrl)
    {
        if (fileName == null) throw new ArgumentNullException("fileName");
        // Upload your file
        using (var webClient = new WebClient())
        {
            webClient.UploadFileAsync(new Uri(targetUrl), fileName);
        }
    }
}

UploadHandlercallback如果你不熟悉这个词,我猜你会很快发现它很有用,因为定义了上传,你不会取决于MyPeriodicUploader在这种情况下会提供的实施;有时候它不适合你的需要,所以自己定义它真的很有用。

我在UploadHandler()中添加了一个非常简单的上传器作为示例。

注意,我使用了Action<string,string>,第一个参数是文件名,第二个参数是目标URL。该类将优雅地失败,如果没有定义文件名和目标URL,则操作将不会发生。

如果您愿意,请标记答案,如果还有其他内容更新您的问题并提供更多详细信息,那么我可以提供帮助。

相关问题