user3505081
user3505081

Reputation: 13

How to set a periodic task through my application?

I would like to implement a periodic file posting function to my application. For example, it uploads a certain text file in every 5 mins. So I am thinking some sort of manager that can handle time. I understand how to use Timer() method in c#, So how do I keep track on my timer through my application running? What will be the appropriate approach for such process?

Upvotes: 1

Views: 121

Answers (1)

aybe
aybe

Reputation: 16692

Welcome to StackOverflow :D

I am assuming that you're using Windows Forms.

Here's an example on how to achieve this :

A periodic uploader for which you can set the interval, the upload handler and manage it (start/stop)

The upload handler will be a method on your side where you do the upload, this is great in the sense that this class does not need to know about it, it just calls it. In other terms 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;
    }
}

Now you want it available for your whole application, open Program.cs and create a property of it there :

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

Then on your form use it like this :

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

UploadHandler is a callback if you're not familiar with the term I guess you'll quickly find it useful because you define the uploading, you won't depend of the implementation that MyPeriodicUploader would provide if it was the case; sometimes it would not fit your needs so defining it yourself is really useful.

I've put a really simple uploader in UploadHandler() as an example.

Note, I have used Action<string,string>, the first parameter is the file name, the second the target URL. The class will fail gracefully, if none of the file name and target url are defined, the operation will simply not happen.

Mark the answer if you like it, if there's something else update your question with more details so I can help.

Upvotes: 2

Related Questions