Search Unity

polling a www url?

Discussion in 'Scripting' started by grka, Feb 14, 2016.

  1. grka

    grka

    Joined:
    Jan 14, 2015
    Posts:
    80
    Hi

    I hope someone can help me. Since my provider doesn't offer websockets like node.js I can only poll my php scripts from the server to check if a value in my database has changed. Since I need the update only ever 5 oder 10 minutes it shouldn't be a big problem but I don't know how to implement the polling in Unity. I made a gameobject with my script:
    Code (csharp):
    1.  
    2. public class Polling : MonoBehaviour {
    3.  
    4.   Thread WorkerThread;
    5.   bool m_bEnd = false;
    6.    
    7.    
    8.   void Start () {
    9.   WorkerThread = new Thread(new ThreadStart(PollData));
    10.   WorkerThread.Start();
    11.  
    12.   }  
    13.    
    14.  
    15.   void PollData()
    16.   {
    17.   while (m_bEnd == false)
    18.   {
    19.   StartCoroutine(GetDataFromServer());
    20.   Thread.Sleep(600000); // poll Server only after 10 min
    21.   }
    22.    
    23.   }
    24.  
    25.  
    26.   private IEnumerator GetDataFromServer()
    27.   {
    28.   string strUrl;
    29.   WWW www;
    30.    
    31.    
    32.   strUrl = "http://www.myserver.de/myscript.php";
    33.  
    34.    
    35.   www = new WWW(strUrl); //GET data is sent via the URL
    36.  
    37.   while (!www.isDone && string.IsNullOrEmpty(www.error))
    38.   {
    39.   yield return null;
    40.   }
    41.  
    42.          // Do something with the results
    43.   // ...
    44.  
    45.   }
    46.  
    47.   void OnApplicationQuit()
    48.   {
    49.   m_bEnd = true;
    50.   }
    51.  
    52.  
    53. }
    54.  
    Well when I added some debug logs then I could see the thread is sleeping for 10 minutes and then he woke up like I expected it. But when I added the www request I can see that the request is never called. I guess the reason is that the thread goes to sleep after calling the coroutine but I don't know what other way I could implement a polling
     
  2. notoriousnary

    notoriousnary

    Joined:
    Jul 16, 2015
    Posts:
    9
    have you taken a look at InvokeRepeating? all you need to pass is the method name and to floats for the timers
     
  3. grka

    grka

    Joined:
    Jan 14, 2015
    Posts:
    80
    Thank you this solved my problem :)
     
    notoriousnary likes this.