Question

I have a Windows Forms application that sends email. Each email has a send time (dateTime).

I want to create a scheduled task in Windows to run a query on my database daily and get emails that should be sent that day.

I want to create an .exe file from a function that does this job, and then set scheduler to run that .exe file daily.

How can I do this?

Is this a correct way of doing a job in at a scheduled time?

Was it helpful?

Solution

I wrote an application that does the similar thing. That is a Windows Forms application that may be used in an interactive way, but also may be run as a scheduled task.

Here is my Program.cs:

static class Program
{
    static void Main(string[] args)
    {
        if (args.Length == 0)
        {
            autoStart = false;
        }
        else if (args[0] == "AUTO")
        {
            autoStart = true;
        }
        Application.Run(new frmMain());
    }

    public static bool autoStart;
}

To run program in interactive mode, the program is executed by a double click on its EXE file.

When you want to call it from a scheduled task, supply parameter AUTO when calling the program.

When run as a scheduled task no input/output operation should be done, i.e. MessageBox.Show or similar are strictly forbidden.

Event handler for loading the form:

private void frmMain_Load(object sender, EventArgs e)
{
     // Initialization of fields in frmMain
     .
     .



    if (Program.autoStart)
    {
        MailSend();
        Application.Exit();
    }
}

Event handler for interactive work:

private void btnMailSend_Click(object sender, EventArgs e)
{
    MailSend();
}

Function that sends mail:

private void MailSend()
{

    // Code to prepare and send mail
    //
    .
    .

    if (!Program.autoStart)
    {
        MessageBox.Show("Mail sent to recipients");
    }
}

OTHER TIPS

Create a console application. This builds to a simple .exe file. Then schedule the console application in your Windows scheduler.

If you want to share the "mail" logic, you can put it in a .dll file and use the .dll file in both projects.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top