0

Mono for Android を使用して、5 秒ごとにメソッドを実行する必要があります。Android にスケジュールされたタイマーはありますか? このコードを試しましたが、起動に失敗しました:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Glass.Core.Interfaces;
using Glass.Core;
using Java.Util;

namespace Glass.UI.AN
{
[Application(Label = "Glass", Icon = "@drawable/icon")]
public class GlassApplication : Application
{
    Context context;

    public GlassApplication (IntPtr handle, JniHandleOwnership transfer)
        : base(handle, transfer)
    {
        this.context = BaseContext;
    }

    public override void OnCreate ()
    {
        base.OnCreate ();
        Timer timer = new Timer ();
        timer.ScheduleAtFixedRate (new CustomTimerTask(context), new Date(DateTime.Now.Year, DateTime.Now.Month, 
        DateTime.Now.Day, DateTime.Now.Hour, DateTime.Now.Minute), 5000);
    }
}

public class CustomTimerTask: TimerTask
{
    Context context;

    public CustomTimerTask(Context context)
    {
        this.context = context;
    }

    public override void Run ()
    {
        GlassWebServiceProvider p = new GlassWebServiceProvider (context);
        p.SendCardReaders ();
    }
}

}

4

2 に答える 2

0

なぜ使用しないのSystem.Timers.Timerですか?

var timer = new Timer();
//What to do when the time elapses
timer.Elapsed += (sender, args) => FireTheMissiles();
//How often (5 sec)
timer.Interval = 5000;
//Start it!
timer.Enabled = true;

private void FireTheMissiles()
{
    //But I'm le tired...
}

Task新しいorを作成し、Thread毎回 5 秒間スリープさせる別のアプローチ:

Task.Factory.StartNew(() =>
    {
        while (true)
        {
            // do some stuff
            Thread.Sleep(TimeSpan.FromSeconds(5));
        }
    });

ThreadPool.QueueUserWorkItem(thread =>
    {
        while (true)
        {
            // do some stuff
            Thread.Sleep(TimeSpan.FromSeconds(5));
        }
    });
于 2013-05-02T20:17:40.203 に答える