SoFunction
Updated on 2025-03-07

C# timed running program sharing (timed program)

1) Add a reference file to our project: (dll defines an ITask interface, and defines two methods Initialize and HandleConditionsMetEvent);

2) Create a time-triggered class: (the class name is defined by yourself), and this class must implement interface ITask. The specific code is as follows:

Copy the codeThe code is as follows:

public class SyncTask : ITask
{
//Accept the variables of the passed parameters
private string configName;

    /// <summary>
/// Specific operation code
/// </summary>
public void HandleConditionsMetEvent(object sender, ConditionsMetEventArgs e)
{
try
{
// Here is the specific operation
}
catch (Exception ex)
{
//Top an exception and record the error log
}
}

/// <summary>
/// Initialization
/// </summary>
/// <param name="schedule"></param>
/// <param name="parameters">parameters (this parameter is passed when the timed setting is triggered)</param>
public void Initialize(ScheduleDefinition schedule, object parameters)
{
//Initialize variables through passed parameters
configFileName = ();
try
{
//Initialization specific code
}
catch (Exception e)
{
//Top an exception and record the error log
}
}
}

3) Configuration file, configuration file parameter setting instructions:

a.  <at></at> is a Task. If different programs are triggered at different times, multiple <at> need to be set; name: is the name of each <at>, which can be named according to your needs; month: in which month the Task is triggered, * means that it is triggered every month; day of Month: what day of each month is triggered, * means that it is triggered every day; day of Week: how many hours of each week is triggered, * means that it is triggered every day; hour: how many minutes of each day is triggered, * means that it is triggered once every hour; minute: how many minutes of each hour is triggered, 58 means that it is triggered 58 minutes of each hour; second: how many seconds of each minute is triggered.

b. <task> is the class that needs to be triggered, type: "The detailed address of the class that needs to be triggered (project name. folder name. class name), project name, Version, Culture, PublicKeyToKen", parameters: the parameters that need to be passed, if the parameter is not passed, it can be set to "";

Copy the codeThe code is as follows:

    <taskSchedulerEngine>
    <schedule>
      <at name="TaskName" month="*" dayOfMonth="*" dayOfWeek="*" hour="*" minute="58" second="0" kind="Local">
        <execute>
          <task type=", Test, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" parameters="" />
        </execute>
      </at>
    </schedule>
</taskSchedulerEngine>

4) The main program starts the timing program:

Copy the codeThe code is as follows:

();

OK, so far, a complete timing program has been finished.