Кварцевое задание не выполняется с использованием.net

Я использую Quartz в приложении-службе Windows. Код, который я использовал, будет работать в консольном приложении, но при вставке для выполнения задания и без отправки электронного письма.

    public partial class Service1 : ServiceBase
    {
        ISchedulerFactory sf = new StdSchedulerFactory();
        IScheduler schd;
        public Service1()
        {
            InitializeComponent();
            if(!System.Diagnostics.EventLog.SourceExists("MySource"))
            {
                System.Diagnostics.EventLog.CreateEventSource("MySource", "MyNewLog");
            }
            eventLog1.Source = "MySource";
            eventLog1.Log = "MyNewLog";
            CanPauseAndContinue = true;
        }

        protected override void OnStart(string[] args)
        {
            eventLog1.WriteEntry("In OnStart");
            schd = sf.GetScheduler();
            schd.Start();

            IJobDetail job = JobBuilder.Create<HelloJob>()
                .WithIdentity("checkThis", "groupThis")
                .Build();

            ITrigger trigger = TriggerBuilder.Create()
                .WithIdentity("triggerThis", "groupThis")
                .WithSimpleSchedule(x => x
                    .WithIntervalInSeconds(5)
                    .RepeatForever())
                .Build();
            schd.ScheduleJob(job, trigger);
        }

        protected override void OnStop()
        {
            var jobKey = new JobKey("checkThis","groupThis");
            eventLog1.WriteEntry("In OnStop");
            schd.PauseJob(jobKey);
            eventLog1.WriteEntry("Job Stopped");
        }
        protected override void OnPause()
        {
            eventLog1.WriteEntry("In OnPause");
            schd.PauseAll();
        }
        protected override void OnContinue()
        {
            base.OnPause();
            eventLog1.WriteEntry("In OnContinue");
            schd.ResumeAll();
        }
        public class HelloJob : IJob
        {
            public void Execute(IJobExecutionContext context)
            {
                string body = "Windows Service is working."; // Message you would like to send out
                var fromAddress = new MailAddress("**************************@gmail.com", "**********");  // Address were sending the email from 
                var toAddress = new MailAddress("***************@vtext.com", "************"); // Address were sending the email to
                const string fromPassword = "*************"; // Password for the address kwere sending from
                const string subject = ""; // Subject of the email were sending (Note: In texts subjects will show up with parenthesis)
                string connectionString = "*******************************";
                using (SqlConnection connection = new SqlConnection(connectionString))
                using (SqlCommand command = new SqlCommand("SELECT * FROM AddressInformation a JOIN Orders o ON o.UserID = a.UserID JOIN Products p ON p.ProductID = o.ProductID WHERE [Email Address] IS NOT NULL", connection))
                {
                    connection.Open();
                    using (SqlDataReader reader = command.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            body += "\nCustomer name:" + reader["CustomerName"].ToString() + " Product: " + reader["ProductName"].ToString();
                        }
                    }
                }
                var smtp = new SmtpClient // Create an instance of smtp used to send the email (Simple Mail Transfer Protocol (SMTP) is an Internet standard for electronic mail (e-mail) transmission.)
                {
                    Host = "smtp.gmail.com",  // Gets or sets the name or IP address of the host used for SMTP transactions
                    Port = 587,  // Gets or sets the port used for SMTP transactions 
                    EnableSsl = true,    //Specify whether the SmtpClient uses Secure Sockets Layer (SSL) to encrypt the connection.
                    DeliveryMethod = SmtpDeliveryMethod.Network,  //Specifies how outgoing email messages will be handled.(Email is sent through the network to an SMTP server.)
                    UseDefaultCredentials = false, //Gets or sets a Boolean value that controls whether the DefaultCredentials are sent with requests. (DefaultCredentials represents the system credentials for the current security context in which the application is running. )
                    Credentials = new NetworkCredential(fromAddress.Address, fromPassword) //Provides credentials for password-based authentication schemes.
                };
                using (var message = new MailMessage(fromAddress, fromAddress) //Creates a MailMessage instance from the to and from Addresses
                {
                    Subject = subject, // Subject of the message
                    Body = body  // Body of the message
                })
                {
                    smtp.Send(message); //sends a mesage using our instance of SmtpClient
                }
            }
        }
    }

Мне было любопытно, кто-нибудь знал, почему мое сервисное приложение не отправляло электронные письма, а консольное приложение будет. Любая помощь приветствуется!

1 ответ

Я давал разрешение локальной системе приложения-службы только тогда, когда ему требовались разрешения пользователя для подключения к базе данных. Мне также нужно было иметь конструктор для моей работы, иначе он не будет выполняться в приложениях-службах Windows!

Другие вопросы по тегам