Windows服务状态正在运行但无法正常工作

时间:2019-03-08 10:17:50

标签: c# windows-services

几天(例如3天左右)后,我的Windows服务仅停止执行系统。计时器事件不再触发,但该服务显示为正在运行。另外,我的日志文件甚至都没有创建,因此不会引发任何错误并记录日志。我在最高级别和第二高级别以及构造函数OnStart和OnStop中都有尝试捕获。请在下面查看我的代码。

有什么想法会导致这种情况吗?

public partial class BetGamesFeedService : ServiceBase
    {
        private Timer _gamesTimer;
        private Timer _nextDrawTimer;
        private Timer _drawResultsTimer;
        private Timer _plannedScheduleTimer;

        private static readonly log4net.ILog log =
            log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        public BetGamesFeedService()
        {
            try
            {
                log4net.Config.XmlConfigurator.Configure();

                //Games Timer
                _gamesTimer = new Timer(Convert.ToInt32(ConfigurationManager.AppSettings["GamesInterval"]));
                _gamesTimer.Elapsed += GamesTimerOnElapsed;
                _gamesTimer.Enabled = true;

                //Next Draw Timer
                _nextDrawTimer = new Timer(Convert.ToInt32(ConfigurationManager.AppSettings["NextDrawInterval"]));
                _nextDrawTimer.Elapsed += NextDrawTimerOnElapsed;
                _nextDrawTimer.Enabled = true;

                //Draw Results Timer
                _drawResultsTimer = new Timer(Convert.ToInt32(ConfigurationManager.AppSettings["DrawResultsInterval"]));
                _drawResultsTimer.Elapsed += DrawResultsTimerOnElapsed;
                _drawResultsTimer.Enabled = true;

                //Planned Schedule Timer
                _plannedScheduleTimer = new Timer(Convert.ToInt32(ConfigurationManager.AppSettings["PlannedScheduleInterval"]));
                _plannedScheduleTimer.Elapsed += PlannedScheduleTimerOnElapsed;
                _plannedScheduleTimer.Enabled = true;

                InitializeComponent();

#if DEBUG
                OnStart(null);
#endif
            }
            catch (Exception ex)
            {
                log.Error(ex.ToString());
            }
        }

        protected override void OnStart(string[] args)
        {
            try
            {
                _gamesTimer.Start();
                _nextDrawTimer.Start();
                _drawResultsTimer.Start();
                _plannedScheduleTimer.Start();
            }
            catch (Exception ex)
            {
                log.Error(ex.ToString());
            }
        }

        protected override void OnStop()
        {
            try
            {
                _gamesTimer.Stop();
                _nextDrawTimer.Stop();
                _drawResultsTimer.Stop();
                _plannedScheduleTimer.Stop();
            }
            catch (Exception ex)
            {
                log.Error(ex.ToString());
            }
        }
        private async void GamesTimerOnElapsed(object sender, ElapsedEventArgs elapsedEventArgs)
        {
            try
            {
                var GamesOn = Convert.ToBoolean(ConfigurationManager.AppSettings["GamesIntervalOn"]);
                if (!GamesOn) return;

                var betGames = new Bl.WindowsService.BetGames();
                await betGames.GetGamesAndAddToDatabase();
            }
            catch(Exception ex)
            {
                log.Error(ex.ToString());
            }
        }

        private async void NextDrawTimerOnElapsed(object sender, ElapsedEventArgs elapsedEventArgs)
        {
            try
            {
                var betGames = new Bl.WindowsService.BetGames();
                await betGames.GetNextDrawAndAddToDatabase(Game.Lucky5);
                await betGames.GetNextDrawAndAddToDatabase(Game.Lucky7);
                await betGames.GetNextDrawAndAddToDatabase(Game.Lucky6);
                await betGames.GetNextDrawAndAddToDatabase(Game.WheelOfFortune);
            }
            catch(Exception ex)
            {
                log.Error(ex.ToString());
            }
        }

        private async void DrawResultsTimerOnElapsed(object sender, ElapsedEventArgs elapsedEventArgs)
        {
            try
            {
                var betGames = new Bl.WindowsService.BetGames();
                await betGames.GetDrawResultsAndAddToDatabase(Game.Lucky5);
                await betGames.GetDrawResultsAndAddToDatabase(Game.Lucky7);
                await betGames.GetDrawResultsAndAddToDatabase(Game.Lucky6);
                await betGames.GetDrawResultsAndAddToDatabase(Game.WheelOfFortune);
            }
            catch(Exception ex)
            {
                log.Error(ex.ToString());
            }
        }

        private async void PlannedScheduleTimerOnElapsed(object sender, ElapsedEventArgs elapsedEventArgs)
        {
            try
            {
                var betGames = new Bl.WindowsService.BetGames();
                await betGames.GetScheduledDrawsAndAddToDatabase(Game.Lucky5);
                await betGames.GetScheduledDrawsAndAddToDatabase(Game.Lucky7);
                await betGames.GetScheduledDrawsAndAddToDatabase(Game.Lucky6);
                await betGames.GetScheduledDrawsAndAddToDatabase(Game.WheelOfFortune);
            }
            catch(Exception ex)
            {
                log.Error(ex.ToString());
            }
        }
    }
public class BetGames
    {
        private readonly int _partnerId =
            Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["PartnerId"]);

        private readonly string _secretKey = System.Configuration.ConfigurationManager.AppSettings["SecretKey"];
        private readonly int _shopId = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["ShopId"]);

        private readonly string[] _method =
        {
            "get_screen_urls", "get_games", "ticket_buy", "ticket_check",
            "ticket_payout", "ticket_return"
        };

        private const string Language = "en";
        private const string Currency = "eur";

        private static readonly log4net.ILog log =
            log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        public async Task GetGamesAndAddToDatabase()
        {
            try
            {
                const int methodIndex = 1;
                var request = new GetGamesRequest
                {
                    partner_id = _partnerId,
                    method = _method[methodIndex],
                    language = Language,
                    timestamp = GetTimestamp(),
                    @params = new BaseParams
                    {
                        currency = Currency,
                        shop_id = _shopId
                    }
                };
                request.signature = GetSignature(methodIndex, request.timestamp, request.@params);

                var api = new BetGamesAPI();
                var response = await api.GetGames(request);

                if (response == null)
                {
                    log.Info("GetGamesAndAddToDatabase(): No Data Returned.");
                    return;
                }

                if (response.response_code != 200)
                {
                    throw new Exception("response.response_code does not indicate success." + Environment.NewLine +
                                        "Response Code: " + response.response_code + Environment.NewLine +
                                        "Response Error: " + response.error_message);
                }

                var games =
                    new JavaScriptSerializer().Deserialize(response.response.ToString(), typeof(List<Bo.Models.Game>))
                        as List<Bo.Models.Game>;

                //Add data to database
                foreach (var game in games)
                {
                    //@Id
                    var pId = new SqlParameter("@Id", SqlDbType.Int);
                    pId.Value = game.id;

                    //@Name
                    var pName = new SqlParameter("@Name", SqlDbType.VarChar);
                    pName.Value = game.name;

                    //@Type
                    var pType = new SqlParameter("@Type", SqlDbType.VarChar);
                    pType.Value = game.type;

                    //@Items
                    var dtItems = new DataTable();
                    dtItems.Columns.Add("Id", typeof(int));
                    dtItems.Columns.Add("Number", typeof(int));
                    dtItems.Columns.Add("Color", typeof(string));

                    foreach (var item in game.items)
                    {
                        dtItems.Rows.Add(item.id, item.number, item.color);
                    }

                    var pItems = new SqlParameter("@Items", SqlDbType.Structured);
                    pItems.Value = dtItems;
                    pItems.TypeName = "bg.ttItem";

                    //@Odds
                    var dtOdds = new DataTable();
                    dtOdds.Columns.Add("Code", typeof(int));
                    dtOdds.Columns.Add("ItemsCount", typeof(int));
                    dtOdds.Columns.Add("Name", typeof(string));
                    dtOdds.Columns.Add("Value", typeof(decimal));

                    foreach (var odd in game.odds)
                    {
                        dtOdds.Rows.Add(odd.code, odd.items_count, odd.name, odd.value);
                    }

                    var pOdds = new SqlParameter("@Odds", SqlDbType.Structured);
                    pOdds.Value = dtOdds;
                    pOdds.TypeName = "bg.ttOdd";

                    using (var db = new BetGamesEntities())
                    {
                        var cmd = db.Database.Connection.CreateCommand();
                        cmd.CommandText = "bg.InsertGameOddsAndItems";
                        cmd.CommandType = CommandType.StoredProcedure;
                        cmd.Parameters.Add(pId);
                        cmd.Parameters.Add(pName);
                        cmd.Parameters.Add(pType);
                        cmd.Parameters.Add(pItems);
                        cmd.Parameters.Add(pOdds);

                        db.Database.Connection.Open();
                        await cmd.ExecuteScalarAsync();
                        db.Database.Connection.Close();
                    }
                }
            }
            catch (Exception ex)
            {
                log.Error(ex.ToString());
            }
        }

        private string GetSignature(int methodIndex, int timestamp, object _params)
        {
            var jsonEncodedObject = new JavaScriptSerializer().Serialize(_params);
            var signatureBase = _partnerId + _method[methodIndex] + Language + timestamp + jsonEncodedObject;

            //Perform hashing
            using (var hmac = new HMACSHA256(Encoding.ASCII.GetBytes(_secretKey)))
            {
                var hash = hmac.ComputeHash(Encoding.ASCII.GetBytes(signatureBase));
                return string.Concat(hash.Select(x => x.ToString("x2")));
            }
        }

        private static int GetTimestamp()
        {
            return (int)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
        }

        public async Task GetNextDrawAndAddToDatabase(Game game)
        {
            try
            {
                var api = new BetGamesAPI();
                var response = await api.GetNextDraw(game);
                if (response == null)
                {
                    log.Info("GetNextDrawAndAddToDatabase(" + game + "): No data returned. Draw Probably currently running.");
                    return;
                }

                var data =
                    new JavaScriptSerializer().Deserialize(response.draws.ToString(), typeof(List<Bo.Models.Draw>)) as List<Bo.Models.Draw>;
                using (var db = new BetGamesEntities())
                {
                    db.InsertOrUpdateDraw(data[0].code, data[0].time.AddHours(2), Convert.ToBoolean(data[0].is_returned),
                        data[0].video_url);
                }
            }
            catch (Exception ex)
            {
                log.Error(ex.ToString());
            }
        }

        public async Task GetDrawResultsAndAddToDatabase(Game game)
        {
            try
            {
                var api = new BetGamesAPI();
                using (var db = new BetGamesEntities())
                {
                    var drawCode = db.GetDrawCode((int)game).FirstOrDefault();
                    if (drawCode == null) return;

                    var response = await api.GetDraws(game, drawCode.Value);
                    if (response == null)
                    {
                        log.Info("GetDrawResultsAndAddToDatabase(" + game + "): No Data Returned");
                        return;
                    }

                    //Insert Data 
                    var data =
                        new JavaScriptSerializer().Deserialize(response.draws.ToString(), typeof(List<Bo.Models.Draw>)) as
                            List<Bo.Models.Draw>;

                    foreach (var draw in data)
                    {
                        //If this draw is Cancelled update the draw status to cancelled
                        if (draw.is_returned == 1)
                        {
                            db.InsertOrUpdateDraw(data[0].code, data[0].time.AddHours(2), Convert.ToBoolean(data[0].is_returned),
                                data[0].video_url);
                        }

                        //if we have results for this draw  
                        if (draw.results_entered == 1)
                        {
                            //@DrawCode
                            var pDrawCode = new SqlParameter("@DrawCode", SqlDbType.BigInt) { Value = draw.code };

                            //@Results
                            var dtResults = new DataTable();
                            dtResults.Columns.Add("BallNumber");
                            dtResults.Columns.Add("BallColor");

                            foreach (var result in draw.results)
                            {
                                dtResults.Rows.Add(result.Number, result.Color);
                            }

                            var pResults = new SqlParameter("@Results", SqlDbType.Structured)
                            {
                                Value = dtResults,
                                TypeName = "bg.ttDrawResult"
                            };

                            var cmd = db.Database.Connection.CreateCommand();
                            cmd.CommandText = "bg.InsertDrawResults";
                            cmd.CommandType = CommandType.StoredProcedure;
                            cmd.Parameters.Add(pDrawCode);
                            cmd.Parameters.Add(pResults);

                            db.Database.Connection.Open();
                            cmd.ExecuteScalar();
                            db.Database.Connection.Close();
                        }
                    }

                }
            }
            catch (Exception ex)
            {
                log.Error(ex.ToString());
            }
        }

        public async Task GetScheduledDrawsAndAddToDatabase(Game game)
        {
            try
            {
                var api = new BetGamesAPI();
                var response = await api.GetScheduledDraws(game);
                if (response == null)
                {
                    log.Info("GetScheduledDrawsAndAddToDatabase(" + game + "): No data returned. Draw Probably currently running.");
                    return;
                }

                var data =
                    new JavaScriptSerializer().Deserialize(response, typeof(List<Bo.Models.ScheduledDraw>)) as List<Bo.Models.ScheduledDraw>;
                using (var db = new BetGamesEntities())
                {

                    var scheduledDrawTable = new DataTable();
                    scheduledDrawTable.Columns.Add("Code", typeof(long));
                    scheduledDrawTable.Columns.Add("Time", typeof(DateTime));

                    foreach (var draw in data)
                    {
                        scheduledDrawTable.Rows.Add(draw.number, draw.time.AddHours(2));
                    }

                    var Draws = new SqlParameter("@Draws", SqlDbType.Structured);
                    Draws.Value = scheduledDrawTable;
                    Draws.TypeName = "bg.ttDraw";

                    var cmd = db.Database.Connection.CreateCommand();
                    cmd.CommandText = "bg.InsertOrUpdateScheduledDraws";
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.Add(Draws);

                    db.Database.Connection.Open();
                    cmd.ExecuteScalar();
                    db.Database.Connection.Close();
                }

            }
            catch (Exception ex)
            {
                log.Error(ex.ToString());
            }
        }

    }

0 个答案:

没有答案