none
Auto logout from an app after 24 hours RRS feed

  • Question

  • Can someone help please with the code below. I added code to App.xaml.cs on the OnStart and when testing it kicks me out of the application after logging in at about 5 seconds. I want to make sure there is nothing wrong with my code that could be causing this to happen. I think it is the Device.StartTimer(TimeSpan.FromSeconds(60), () =>. Should that be Device.StartTimer(TimeSpan.FromHours(24), () => Here is my latest code:

    protected override void OnStart()
             {
                 // Handle when your app starts
                   _sessionStart = DateTime.Now;
    
            Device.StartTimer(TimeSpan.FromSeconds(60), () =>
            {
                DateTime lastTimeUsed = default(DateTime);
                // Check if 24 hours has elapsed
                if ((DateTime.Now - lastTimeUsed).TotalHours > 24)
                {
                    //logout
                    MainPage = new NavigationPage(new LoginPage());
                }
    
                return true; // True = Repeat again, False = Stop the timer
            });

    Thursday, April 11, 2019 8:30 PM

All replies

  • "default(DateTime)" returns January 1 of year 1, more than 2,000 years ago.  DateTime.Now - lastTimeUsed is ALWAYS going to be > 24.

    I don't know how "lastTimeUsed" is defined in your application, but whenever you want to reset the timer, you need to set lastTimeUsed to DateTime.Now, and clearly it can't be local to the lambda.  It has to be a class variable.


    Tim Roberts | Driver MVP Emeritus | Providenza & Boekelheide, Inc.


    • Edited by Tim Roberts Thursday, April 11, 2019 9:57 PM
    Thursday, April 11, 2019 9:54 PM
  • Minor suggestion to modification. You're recommanded to use DateTime.UtcNow for all operations that keep track of time duration in order to prevent consequence caused by DST.
    Friday, April 12, 2019 1:28 AM
    Answerer
  • Hi

    Is your problem solved? If so, please post "Mark as answer" to the appropriate answer, so that it will help other members to find the solution quickly if they face a similar issue.

    Best Regards,

    Jack


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Tuesday, May 7, 2019 8:10 AM
    Moderator