0

I m developing an ASP.NET (with sql server) application. My requirement is to send emails from the host web server (in my case Windows Shared Hosting from Godaddy) at specific intervals - these may be daily or weekly or monthly. Cron tab can't be used because it's Linux command which runs on Linux hosting. Godaddy's Shared hosting doesn't have any Task Scheduler tool. I've tried many times but couldn't get success. I've already used these three codes.

First attempt:

<%@ Application Language="C#" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Threading" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<%@ Import Namespace="System.Timers" %>
<script runat="server">    

    void Application_Start(object sender, EventArgs e) 
    {
        // Code that runs on application startup
        Thread timerThread = new Thread(TimerForNotification);
        timerThread.IsBackground = true;
        timerThread.Priority = ThreadPriority.Highest;
        timerThread.Start();    
    }

    void TimerForNotification()
    {
        //Code that runs on application startup
        System.Timers.Timer timScheduledTask = new System.Timers.Timer();
        timScheduledTask.Interval = 1000 * 60 * 60;   //TimeSpan.FromMinutes(30).Minutes * 1000 * 60;
        timScheduledTask.Enabled = true;
        timScheduledTask.Elapsed += new System.Timers.ElapsedEventHandler(timScheduledTas_Elapsed);       
    }

    void timScheduledTas_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    {
        ConnectionStringSettings conn = ConfigurationManager.ConnectionStrings["myshop_con"];
        SqlConnection con = new SqlConnection(conn.ConnectionString);
        SqlCommand cmd = con.CreateCommand();
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = "insert into dbo.tblUserDetail(UName)VALUES('" + DateTime.Now.ToString() + "')";
        con.Open();
        cmd.ExecuteNonQuery();
        con.Close();  
    }    

</script>

Second attempt:

<%@ Application Language="C#" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Threading" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>


<script runat="server">    

    public class TimerStarter
    {
        private static System.Threading.Timer threadingTimer;
        public static void StartTimer()
        {
            if (null == threadingTimer)
            {
                threadingTimer = new System.Threading.Timer(new TimerCallback(DoActions), HttpContext.Current, 0, 3600000);
            }
        }
        private static void DoActions(object sender)
        {
            ConnectionStringSettings conn = ConfigurationManager.ConnectionStrings["myshop_con"];
            SqlConnection con = new SqlConnection(conn.ConnectionString);
            SqlCommand cmd = con.CreateCommand();
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "insert into dbo.tblUserDetail(UName)VALUES('" + DateTime.Now.ToString() + "')";
            con.Open();
            cmd.ExecuteNonQuery();
            con.Close();  
        }

    }


    void Application_Start(object sender, EventArgs e) 
    {
        TimerStarter.StartTimer();
    }
</script>

Third attempt:

<%@ Application Language="C#" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Threading" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>


<script runat="server">    
    private void NightlyProcess(object o)
    {
        ConnectionStringSettings conn = ConfigurationManager.ConnectionStrings["myshop_con"];
        SqlConnection con = new SqlConnection(conn.ConnectionString);
        SqlCommand cmd = con.CreateCommand();
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = "insert into dbo.tblUserDetail(UName)VALUES('" + DateTime.Now.ToString() + "')";
        con.Open();
        cmd.ExecuteNonQuery();
        con.Close();  
    } 


    void Application_Start(object sender, EventArgs e) 
    {
        System.Threading.TimerCallback tcb = new System.Threading.TimerCallback(NightlyProcess);
        System.Threading.Timer theTimer = new System.Threading.Timer(tcb, null, GetTimerInitialDelay(20, 40), GetTimerRepeatDelay(24));          
    }

    private long GetTimerInitialDelay(int hours, int minutes)
    {
        long startMS, repeatMS, currentMS;
        startMS = (1000 * 60 * 60 * hours) + (1000 * 60 * minutes);
        repeatMS = GetTimerRepeatDelay(24);

        DateTime now = DateTime.Now;
        long currentHours = 1000 * 60 * 60 * now.Hour;
        long currentMinutes = 1000 * 60 * now.Minute;
        long currentSeconds = 1000 * now.Second;
        long currentMilliSeconds = now.Millisecond;
        currentMS = currentHours + currentMinutes + currentSeconds + currentMilliSeconds;
        long delay = startMS - currentMS;
        if (delay < 0)
        {
            return repeatMS + delay;
        }
        else
        {
            return delay;
        }
    }

    private long GetTimerRepeatDelay(int hours)
    {
        long repeatMS;
        repeatMS = 1000 * 60 * 60 * hours;
        return repeatMS;
    }
</script>

How might I get these emails sent at these intervals?

Nightfirecat
  • 11,432
  • 6
  • 35
  • 51
user2791156
  • 41
  • 2
  • 10

2 Answers2

0

What you’re trying to achieve is not possible without some kind of task scheduler or windows service running in the background.

What you can try to do is to create a web page that when requested will send a certain number of emails and then to invoke this page using some third party ping service or some very simple script running from your local PC.

Note that this is only a workaround and that a solid solution needs more access on the server with VPS or dedicated server hosting.

Another thing you can try is some kind of third party service that will send emails for you. You can try mail chimp – they have free version with limited number of emails per month and there is also an API you can use.

Stanley Norman
  • 133
  • 1
  • 1
  • 5
0

Very old question but may help some new readers. In ASP.NET we can simulate Windows Service to run scheduled jobs.

It is very strange but cache items are very usefull for this purpose.

Logic is very simple and different.

  1. Create a cache object

    private const string DummyCacheItemKey = "GagaGuguGigi";
    
    protected void Application_Start(Object sender, EventArgs e)
    {
         RegisterCacheEntry();
    }
    
    private bool RegisterCacheEntry()
    { 
      if( null != HttpContext.Current.Cache[ DummyCacheItemKey ] ) 
           return false;
    
      HttpContext.Current.Cache.Add( DummyCacheItemKey, "Test", null, 
      DateTime.MaxValue, TimeSpan.FromMinutes(1), 
      CacheItemPriority.Normal,
      new CacheItemRemovedCallback( CacheItemRemovedCallback ) );
    
      return true;
    }
    
  2. When the cache object has been removed, raise a callback function to run your scheduled jobs.

    public void CacheItemRemovedCallback(string key, 
                                     object value, CacheItemRemovedReason reason)
    {
      Debug.WriteLine("Cache item callback: " + DateTime.Now.ToString() );
      HitPage()
    // Do the service works
    
    DoWork();
    }
    
  3. On Callback function you have to set up cache again. For this purpose, create a dummy page and visit via webclient.

    private const string DummyPageUrl = 
               "http://localhost/TestCacheTimeout/WebForm1.aspx";
    
    private void HitPage()
    {
        WebClient client = new WebClient();
        client.DownloadData(DummyPageUrl);
    }
    
  4. On Application_BeginRequest check whether it is dummy page or not.

    protected void Application_BeginRequest(Object sender, EventArgs e)
    {
        // If the dummy page is hit, then it means we want to add another item
    
        // in cache
    
         if( HttpContext.Current.Request.Url.ToString() == DummyPageUrl )
         {
            // Add the item in cache and when succesful, do the work.
    
            RegisterCacheEntry();
         }
     }
    

Here is the details how you can schedule your activities with pure ASP.NET

ahmet
  • 702
  • 1
  • 10
  • 29