使用C#建立windows服務續之使用Topshelf優化Windows服務

qq_42606051發表於2018-09-26

前言:

之前寫了一篇“使用C#建立windows服務”,https://www.cnblogs.com/huangwei1992/p/9693167.html,然後有博友給我推薦了一個開源框架Topshelf。

寫了一點測試程式碼,發現Topshelf框架確實在建立windows服務上非常好用,於是就對我之前的程式碼進行了改造。

開發流程:

1.在不使用Topshelf框架的情況下,我們需要建立Windows服務程式,在這裡我們只需要建立一個控制檯程式就行了

2.新增引用

使用程式安裝命令:

  • Install-Package Topshelf

直接在NuGet包管理器中搜尋 Topshelf,點選安裝即可:

3.新建核心類CloudImageManager

主要方法有三個:LoadCloudImage、Start、Stop,直接貼程式碼

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

/// <summary>

    /// 功能描述    :衛星雲圖下載管理器 

    /// 創 建 者    :Administrator

    /// 建立日期    :2018/9/25 14:29:03

    /// 最後修改者  :Administrator

    /// 最後修改日期:2018/9/25 14:29:03

    /// </summary>

    public class CloudImageManager

    {

        private string _ImagePath = System.Configuration.ConfigurationManager.AppSettings["Path"];

        private Timer _Timer = null;

        private double Interval = double.Parse(System.Configuration.ConfigurationManager.AppSettings["Minutes"]);

        public CloudImageManager()

        {

            _Timer = new Timer();

            _Timer.Interval = Interval * 60 * 1000;

            _Timer.Elapsed += _Timer_Elapsed;

        }

        void _Timer_Elapsed(object sender, ElapsedEventArgs e)

        {

            StartLoad();

        }

        /// <summary>

        /// 開始下載雲圖

        /// </summary>

        private void StartLoad()

        {

            LoadCloudImage();

        }

        public void Start()

        {

            StartLoad();

            _Timer.Start();

        }

        public void Stop()

        {

            _Timer.Stop();

        }

        /// <summary>

        /// 下載當天所有衛星雲圖

        /// </summary>

        private void LoadCloudImage()

        {

            CreateFilePath();//判斷資料夾是否存在,不存在則建立

            //獲取前一天日期

            string lastYear = DateTime.Now.AddDays(-1).Year.ToString();

            string lastMonth = DateTime.Now.AddDays(-1).Month.ToString();

            if (lastMonth.Length < 2) lastMonth = "0" + lastMonth;

            string lastDay = DateTime.Now.AddDays(-1).Day.ToString();

            if (lastDay.Length < 2) lastDay = "0" + lastDay;

            //獲取當天日期

            string year = DateTime.Now.Year.ToString();

            string month = DateTime.Now.Month.ToString();

            if (month.Length < 2) month = "0" + month;

            string day = DateTime.Now.Day.ToString();

            if (day.Length < 2) day = "0" + day;

            //設定所有檔名

            string[] dates0 = { lastYear + "/" + lastMonth + "/" + lastDay, year + "/" + month + "/" + day };

            string[] dates = { lastYear + lastMonth + lastDay, year + month + day };

            string[] hours = { "00""01""02""03""04""05""06""07""08""09""10""11""12""13""14""15""16""17""18""19""20""21""22""23" };

            string[] minutes = { "15""45" };

            int hLength = hours.Count();

            //遍歷下載當天所有線上雲圖

            for (int i = 0; i < 2; i++)

            {

                string date = dates[i];

                string date0 = dates0[i];

                for (int j = 0; j < hLength; j++)

                {

                    string hour = hours[j];

                    for (int k = 0; k < 2; k++)

                    {

                        string minute = minutes[k];

                        string imageUrl = @"http://image.nmc.cn/product/" + date0 + @"/WXCL/SEVP_NSMC_WXCL_ASC_E99_ACHN_LNO_PY_" + date + hour + minute + "00000.JPG";

                        string[] s = imageUrl.Split('/');

                        string imageName = s[s.Count() - 1];

 

                        HttpWebRequest request = HttpWebRequest.Create(imageUrl) as HttpWebRequest;

                        HttpWebResponse response = null;

                        try

                        {

                            response = request.GetResponse() as HttpWebResponse;

                        }

                        catch (Exception)

                        {

                            continue;

                        }

 

                        if (response.StatusCode != HttpStatusCode.OK) continue;

                        Stream reader = response.GetResponseStream();

                        FileStream writer = new FileStream(_ImagePath + imageName, FileMode.OpenOrCreate, FileAccess.Write);

                        byte[] buff = new byte[512];

                        int c = 0; //實際讀取的位元組數

                        while ((c = reader.Read(buff, 0, buff.Length)) > 0)

                        {

                            writer.Write(buff, 0, c);

                        }

                        writer.Close();

                        writer.Dispose();

                        reader.Close();

                        reader.Dispose();

                        response.Close();

                    }

                }

            }

        }

        /// <summary>

        /// 判斷資料夾是否存在,不存在則建立

        /// </summary>

        private void CreateFilePath()

        {

            if (Directory.Exists(_ImagePath))

            {

                ClearImages();

                return;

            }

            else

            {

                Directory.CreateDirectory(_ImagePath);

            }

        }

        /// <summary>

        /// 清空資料夾下所有檔案

        /// </summary>

        private void ClearImages()

        {

            try

            {

                DirectoryInfo dir = new DirectoryInfo(_ImagePath);

                FileSystemInfo[] fileinfo = dir.GetFileSystemInfos();  //返回目錄中所有檔案和子目錄

                foreach (FileSystemInfo i in fileinfo)

                {

                    if (i is DirectoryInfo)            //判斷是否資料夾

                    {

                        DirectoryInfo subdir = new DirectoryInfo(i.FullName);

                        subdir.Delete(true);          //刪除子目錄和檔案

                    }

                    else

                    {

                        File.Delete(i.FullName);      //刪除指定檔案

                    }

                }

            }

            catch (Exception e)

            {

                Console.WriteLine(e.Message);

            }

        }

    }

 然後在Program.cs中呼叫:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

static void Main(string[] args)

        {

            HostFactory.Run(x =>                                 //1

            {

                x.Service<CloudImageManager>(s =>                        //2

                {

                    s.ConstructUsing(name => new CloudImageManager());     //3

                    s.WhenStarted(tc => tc.Start());              //4

                    s.WhenStopped(tc => tc.Stop());               //5

                });

                x.RunAsLocalSystem();                            //6

 

                x.SetDescription("衛星雲圖實時下載工具");        //7

                x.SetDisplayName("CloudImageLoad");                       //8

                x.SetServiceName("CloudImageLoad");                       //9

            });

        }

可以看到呼叫的時候主要涉及到CloudImageManager類中的建構函式、Start方法以及Stop方法

安裝、執行和解除安裝:

在Topshelf框架下進行服務的這些操作相對而言就簡單多了

安裝:Topshelf.CloudImageLoad.exe install

啟動:Topshelf.CloudImageLoad.exe start

解除安裝:Topshelf.CloudImageLoad.exe uninstall

操作介面如下:(注意:必須用管理員身份執行命令提示符)

在這裡只貼出了安裝命令的截圖,其他命令相信就不用多說了。

檢視服務列表,這時我們的服務就已經安裝成功了

 

參考連結:

http://www.cnblogs.com/jys509/p/4614975.html

form:https://www.cnblogs.com/huangwei1992/p/9704732.html

鄭州人流多少錢

鄭州人流多少錢

鄭州人流醫院

鄭州做人流哪家好

相關文章