C#windows服务问题

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.Caching;
using JoyTools;

namespace JoyWorkAutoRequestService
{
    public partial class Service1 : ServiceBase
    {
        public Service1()
        {
            InitializeComponent();
        }
        public void ReadPage(string PageUrl)
        {
            try
            {
                //string PageUrl = "地址/testess.aspx"; //需要获取源代码的网页
                WebRequest request = WebRequest.Create(PageUrl); //WebRequest.Create方法,返回WebRequest的子类HttpWebRequest
                WebResponse response = request.GetResponse(); //WebRequest.GetResponse方法,返回对 Internet 请求的响应
                Stream resStream = response.GetResponseStream(); //WebResponse.GetResponseStream 方法,从 Internet 资源返回数据流。
                Encoding enc = Encoding.GetEncoding("utf-8"); // 如果是乱码就改成 utf-8 / GB2312
                StreamReader sr = new StreamReader(resStream, enc); //命名空间:System.IO。 StreamReader 类实现一个 TextReader (TextReader类,表示可读取连续字符系列的读取器),使其以一种特定的编码从字节流中读取字符。
                string get = sr.ReadToEnd(); //输出(HTML代码),ContentHtml为Multiline模式的TextBox控件
                resStream.Close();
                sr.Close();

                WriteInfo(get, PageUrl);
            }
            catch (Exception ex)
            {
                WriteInfo(ex.Message, "Exception");
            }
        }
        public static object GetCache(string cacheKey)
        {
            var objCache = HttpRuntime.Cache.Get(cacheKey);
            return objCache;
        }
        public static void SetCache(string cacheKey, object objObject, int timeout = 7200)
        {
            try
            {
                if (objObject == null) return;
                var objCache = HttpRuntime.Cache;
                //相对过期  
                //objCache.Insert(cacheKey, objObject, null, DateTime.MaxValue,  new TimeSpan(0, 0, timeout), CacheItemPriority.NotRemovable, null);  
                //绝对过期时间  
                objCache.Insert(cacheKey, objObject, null, DateTime.UtcNow.AddSeconds(timeout), TimeSpan.Zero, CacheItemPriority.High, null);
            }
            catch (Exception)
            {
                //throw;  
            }
        }
        System.Timers.Timer timer1;  //计时器
        private void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            try
            {
                string[] allkey = ConfigurationManager.AppSettings.AllKeys;
                foreach (string key in allkey)
                {
                    string pageAndTime = ConfigurationManager.AppSettings[key].ToString();
                    //单位分钟
                    int timeminite = StringHelper.ConvertObjToInt(pageAndTime.Split('|')[0]);
                    string pageurl = pageAndTime.Split('|')[1];
                    //如果有cache就不执行
                    string cacheKey = "AutoRequestItem_" + key;
                    if (GetCache(cacheKey) != null && GetCache(cacheKey).ToString() == "1")
                    {
                    }
                    else
                    {
                        ReadPage(pageurl);
                        SetCache(cacheKey, 1, 60 * timeminite);
                    }
                }
            }
            catch (Exception ex)
            {
                WriteInfo(ex.Message, "Exception");
            }
        }
        protected override void OnStart(string[] args)
        {
            //WriteInfo("服务启动3");
            timer1 = new System.Timers.Timer();
            timer1.Interval = 10000;  //设置计时器事件间隔执行时间  每隔三秒执行一次
            timer1.Elapsed += new System.Timers.ElapsedEventHandler(timer1_Elapsed);
            timer1.Enabled = true;
        }

        protected override void OnStop()
        {
            //WriteInfo("服务停止");
        }

        private void WriteInfo(string info, string filetag)
        {
            JoyTools.FileHelper.SaveFileContent(@"C:\AutoRequestService_Log/", JoyTools.StringHelper.Md5(filetag) + ".txt", $"{DateTime.Now},{info}");
        }
    }
}
定时访问页面地址:页面地址配置文件在App.config里面

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <appSettings>
        <!--2分钟执行一次地址-->
        <add key="PageUrl" value="2|https://hujindev.inf.kim/testess.aspx"/>
        <add key="PageUrl2" value="3|https://hujindev.inf.kim/testess2.aspx"/>
    </appSettings>
    <startup>
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup>
</configuration>

安装语句

CD C:\Windows\Microsoft.NET\Framework\v4.0.30319
InstallUtil E:\地址RequestService\bin\Debug\AutoRequestService.exe

卸载

InstallUtil E:\地址RequestService\bin\Debug\AutoRequestService.exe -u

如果出现权限问题,就应该用管理员身份运行cmd

如果运行时候需要输入账号密码,应该设置任务的一个属性。

测试好像代码里面写Thread开启服务报错。写日志获取路径也报错。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值