c# (.net)計劃任務

來源:互聯網
上載者:User
 剛剛去了一家公司面試,他們讓我上機做一個類似計劃任務的模組,在設定檔裡寫要執行的時間,讓程式定時執行。

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了。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.