Go to my github

c# (.net)计划任务

 刚刚去了一家公司面试,他们让我上机做一个类似计划任务的模块,在配置文件里写要执行的时间,让程序定时执行。

1.建立配置文件App.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <!--设定每月执行计划任务的日期,先设定每月的16号,17号,25号执行-->
    <add key ="DateNum" value ="16,17,25"/>
  </appSettings>
</configuration>

2. 建立PlanWork.cs文件

using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;
using System.Timers;

namespace PlanWork
{
    public class PlanWork
    {
        static void Main(string[] args)
        {
            Myplan mp = new Myplan();


            //*************************************************
            //设定间隔时间是15天,测试的时候设定时间为1000纳秒
            //Timer t = new Timer(15 * 24 * 60 * 60000);
            Timer t = new Timer(1000);
            //*************************************************


            //绑定定时触发的函数
            t.Elapsed += new ElapsedEventHandler(mp.RunMyplan);
            t.Start();
            Console.ReadLine();
        }

    }
    public class Myplan
    {
        public void RunMyplan(Object source, ElapsedEventArgs e)
        {
            //读取配置文件设定的日期时间
            string SetDate = ConfigurationManager.AppSettings["DateNum"].ToString();

            //获取现在的系统时间
            DateTime nowTime = System.DateTime.Now;
            string d = nowTime.Day.ToString(); //取日期

            //比较是否符合设定的时间,SetDate中是否有d的存在
            int i = SetDate.IndexOf(d);
            if (i >= 0)
            {
                //计划任务要执行程序
                Console.Write("\nToday is " + d + " day!");
            }

 

        }

    }
}

这样一个计划任务的小程序就ok了。

posted @ 2010-02-08 16:21  峡谷少爷  阅读(3906)  评论(1编辑  收藏  举报