title: Laravel - Scheduled, Long Running Tasks. High Memory
body: <p>I'm currently writing an application in Laravel and am setting up some scheduled tasks that will be run periodically (artisan commands) -- maybe once or twice a month.  These tasks grab some CSV files using CURL, parse them, and import them into my local MySQL database.</p>
  
  <p>However, a couple of these of these CSV files are quite large -- around 500,000 lines each.  So I have run into some memory issues.</p>
  
  <p>Obviously I can increase the memory in my VM, but i'm wondering how what other practices I can implement to ensure that I don't run out of memory.  If I try to parse the files in chunks, rather than all at once, will each chunk be treated as a separate system process?  Or will it still be treated as one long execution for the server?</p>
  
  <p>EDIT: My current approach.  I'm using <a href="http://csv.thephpleague.com/" rel="nofollow">League CSV</a> for the Parsing.</p>
  
  <pre><code>protected $offset = 1;
  protected $parse_chunk = 10000;
  
  public function parse() 
  {
       $this-&gt;data = [];
       $this-&gt;reader-&gt;setOffset($this-&gt;offset)-&gt;setLimit($this-&gt;parse_chunk)-&gt;fetchAll(function($row, $offset) {
              array_push($this-&gt;data, array_combine($this-&gt;keys, $row));
              $this-&gt;offset = $offset;
       });
  }
  </code></pre>
  
  <p>So currently, the above fetches the first 10000 rows, and does the processing I need, which stores them in  a new <code>$data</code> array.  This data then gets passed to a Import Class, but my scripts are timing out in the parsing currently.</p>
  
  <p>So the above works, but if I put that within a <code>while</code> loop to access all 500,000 records, then it uses too much memory.</p>
  
  <p>Should I be dispatching each chunk to a queue which gets processed in the background?</p>
  
  <p>EDIT: Added Benchmarks</p>
  
  <p>I spent some time testing how long different processes take.  The Parsing had interesting results.  Keep in mind, this is JUST parsing.  So it is not being stored in the DB, but it is being stored in an Array in Memory.</p>
  
  <pre><code>Parsing 1000 records: .017 seconds
  Parsing 10,000 records: .188 seconds
  Parsing 100,000 records: 2.273 seconds
  Parsing 500,000 records: Never completes.
  </code></pre>
  
  <p>I'm using the code above to execute this.  What might cause the parsing to take so long (or perhaps fail) at 500,000 records?</p>