Napi api: Batch API

The spam filter installed on this site is currently unavailable. Per site policy, we are unable to accept new submissions until that problem is resolved. Please try resubmitting the form in a couple of minutes.
Kategória: 
Leírás
Napi api: Batch API

Well, talán harmadjára futok össze a batch apival, és még mindig nem volt zökkenőmentes a barátság, szóval amíg az a betyár sok elem leszalad, amin dolgoztam, levésem gyorsan a tudnivalókat, hogy legközelebb már ne kelljen megint mindenre rájönni.

No akkor batch api:

A batch kötegelt feldolgozást jelent. Drupalon belül úgy is mondhatjuk, hogyha egyszerre annyi adattal kell dolgozni, ami túlnő egy oldalletöltés korlátjain, akkor kell a batch apihoz nyúlni. A képet megnézve valószínű egyébként, hogy egyből leesik, a Drupal melyik részéről is van szó.

Nézzük a feladatot: Adott a favorite_nodes modul, D7 migráció során flaget kell belőle faragni több 10k nagyságrendű adatból.

A batch api maga két fő részből áll. Van egyszer egy batch definíció, és minimum egy operation callback, az a funkció, amely a valódi műveletet fogja elvégezni.

Így néz ki nagyjából egy batch definíció:

[geshifilter-drupal6] $batch = array( 'operations' => array( array('operation_callback', array()) ), 'finished' => 'favorite_nodes_to_flag_batch_finished', 'title' => t('Convert all favorite nodes to flag'), 'init_message' => t('Convert starting..'), 'progress_message' => t('Processed @current out of @total.'), 'error_message' => t('Hmm.. Something could be wrong, sorry, post an issue to module..'), );[/geshifilter-drupal6]

Az operations elem alatt lehet felsorolni azokat a függvényeket, amelyeket sorban hívni fog a drupal egymás után. Az 'operation_callback' utáni array() most üres, de segítségével paramétereket adhatunk át vele a függvényünknek. Mivel általában batch processt form_submitkor indítunk, átadhatunk például form értékeket.

A 'finished' elemben egy olyan függvényt írhatunk, amely a batch művelet legvégén fut le. Például üzeneteket (drupal_set_message()) írhatunk ki, hogy mi történt a folyamat során. Figyi, ez nem array, ebből csak egy van!

Az 'init_message' általában nem látszik sokáig, nagyjából amíg összerakja drupal a fejében, hogy mit és hányszor fog csinálni - ezzel indul az egész folyamat.

Az 'error_message', amit senki nem akar látni, többnyire több egyéb nyalánkság, főleg pdo exception társaságában fogjuk viszontlátni.

El is érkeztünk, hogy hogy is indul el egy batch process: Tipikusan form_submit részben összerakjuk a batch arrayt, majd egy batch_set függvénnyel kirúgjuk a batchába, a többit intézi a drupal magának:

[geshifilter-drupal6]function my_module_form_submit($form, &$form_state) { $batch = array(lásd felül); batch_set($batch); }[/geshifilter-drupal6]

Ezzel elkezdődik az operation része a batchnek. Ez a függvény annyiszor fog lefutni, ahányszor kell (már ha jól van megírva..)
Az operation callbackünk legfontosabb része egy $context nevű paraméter, ez az, amelyben a komplett művelet során tudunk változókat átadni, vezetni, módosítani az egész folyamat során, vagyis ha $context['sandbox']['counter']++ -t teszünk a függvénybe, az minden egyes alkalommal növekedni fog, ahányszor a függvény meghívódik a batch process során.

Ennek a $context paraméternek a következő részeit állítgathatjuk:

$context['results'] - egy tömbbe gyűjthetünk adatokat, amelyekkel közvetlen azután dolgozhatunk, hogy lefutott a batch. Ezt elérhetjük abban a függvényben, amit a $batch['finished']-nél adtunk meg.

$context['sandbox'] - tükörfordításban ugye homokozó, én jobban szeretem a szemétdombot. Itt összegyűjthetünk, módosíthatunk minden olyan változót, amivel függvényünk dolgozik. Például ahogy fentebb is volt már, hogy hányszor futott a process.

$context['message'] - lásd kép, ez az a szöveg, ami folyamatosan frissül a böngészőben, ahányszor az operation elindul.

$context['finished'] - Hogy hány %-nál jár a művelet. Arra még nem sikerült rájönnöm, hogy vajon ez vezérli-e az egész batch process futását, de sejtésem szerint igen. Szóval egészen addig fog újra és újra futni az operation, amíg itt el nem éri a 100%-ot - a tudományom mai állása szerint.

Nézzünk egy ilyen függvényt, és magyarázzunk:

[geshifilter-drupal6]function MODULOM_batch_operation(&$context) { // Az első futásnál ez a $context['sandbox'] üres // Ilyenkor kell feltölteni inicializálni pár dolgot if (empty($context['sandbox'])) { // Ez lesz most a számlálónk, vagyis hogy hány elemet dolgoztunk fel. $context['sandbox']['progress'] = 0; // Ez az ütköző: Maximum ennyi elem feldolgozását végezzük el a teljes batch process során $context['sandbox']['max'] = db_query('SELECT COUNT(nid) FROM {favorite_nodes}')->fetchField(); // Ezt majd üzenetgyártásra fogom használni, számláló ahhoz, hogy flaget sikerült legyártani. $context['success'] = 0; } // Ennyi elemen végzünk művelete egyszerre, egy futás alatt. $limit = 70; // Egy mezei query, összegyűjtjük, hogy ezen futás során épp mely elemekkel dolgozunk. // Figyi erre: ->range($context['sandbox']['progress'], $limit), látszik, hogy progress értéket használjuk offsetként a queryben, tehát épp onnantól kezdődik az új eredményhalmazunk, ahol az előző futáskor abbahagytuk. $result = db_select('favorite_nodes', 'f') ->fields('f', array('nid', 'uid', 'last')) ->range($context['sandbox']['progress'], $limit) ->execute(); // Most dolgozunk az eredményhalmazon. foreach ($result as $row) { // Először növeljük a progresst. $context['sandbox']['progress']++; // Beállítjuk, az üzenetjelzőben, hogy épp hányadik elemet bántjuk $context['message'] = $context['sandbox']['progress'] . ' item processed.'; // Ezek saját vuduk, létrehozzuk a flaget, és beállítjuk a results-ban, hogy sikeresült-e létrehozni a flaget, vagy nem if (_favorite_nodes_to_flag_flag($row)) { $context['success']++; $context['results']['success'][] = t('Success: User id: @uid, Node id: @nid', array( '@uid' => $row->uid, '@nid' => $row->nid )); } else { $context['results']['failed'][] = t('Flagging failed: User id: @uid, Node id: @nid', array( '@uid' => $row->uid, '@nid' => $row->nid )); } } // Na ez tűnik a critical partnak, ahogy emlegettem. Ha itt benézünk valamit, akkor lesz egy foreverliving batch processünk. Szóval figyeljünk, hogy hogyan állítjuk be az ütközőt. if ($context['sandbox']['progress'] != $context['sandbox']['max']) { $context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['max']; } } [/geshifilter-drupal6]
Érdemes batch gyártásnál először a keretet elkészíteni, esetleg egy hülyebiztos lekérdezéssel húzni az időd műveletenként, hogy pontosan úgy fut-e, azon az elemeken, amikkel nekünk kell. Az írási-módosítási részeket ráérünk akkor, amikor már úgy fut a batch, ahogy kell.

Ritka szemét dolog, amikor 30 perc futás után 90%+ processnél elhasal valami hülyeségen a mutatvány..

Hozzászólások

Some insurance providers will

Some insurance providers will certainly allow you to move or mirror your private no claims reward on your electric motor field
policy.

My page ... http://casaen.mx/index.php

A described car is one

A described car is one especially shown on the certificate of car insurance coverage.

My page ... used cars ireland - Anne,

Thanks very interesting blog!

Thanks very interesting blog!

Assume Insurance policy

Assume Insurance policy Services Limited is an independent intermediary/ credit rating broker.

Also visit my site - http://hotel-ejecutivo.com/?option=com_k2&view=itemlist&task=user&id=440841

Many people suppose that

Many people suppose that purchasing mattress is rather like buying a cake that the one factor to contemplate is the design.

It takes Thirty Days for an

It takes Thirty Days for an trade insurance - ibowmangallery.com - policy quote to end,
meanings that you will certainly have some sufficient time to contrast and determine which offer to go for.

Tradewise Insurance Services

Tradewise Insurance Services Ltd is exempt for the content of exterior websites.

my web site - new cars 2017 (Tiara)

Remember: You always have the

Remember: You always have the right tto fire
your lawyers if you feel they are not representing you to your complete satisfaction.
After an accident, particularly if the victim is hospitalized, there is a huge need for cash to pay tthe hospital, the surgeons and for the after care.
No matter the size of the firm, make sure your attorney is actually looking out for your best
interests and not just theirs.

Feel free to surf to my web site ... las vegas personal injury lawyer

And also they could possibly

And also they could possibly be integrateded greater numbers for the price of
solitary human piloted fighter.

My blog - http://politicalcorrectness.org/index.php/The_best_ways_to_Construct_A_Fairer_City.

Whether you are buying new

Whether you are buying new trade insurance uk or
restoring your policy, you must always look around for bargains first.

Whatever the sort of electric

Whatever the sort of electric motor profession company you run, we
could obtain you covered at a competitive cost, assisting you to
keep your expenses down.

Also visit my webpage; http://re.vu/neotituallda1986

However, dietary fat causes

However, dietary fat causes you to produce more galanin, which then tells you to eat more fat.

At Swinton Commercial, we

At Swinton Commercial, we understand that the electric motor trade market is
as diverse as the vehicles it deals with.

Take a look at my website ... new cars coming out

Though they claim that you

Though they claim that you have to go to the very least 18,
the majority of trade insurance online service providers do not
accept candidates under the age of 23.

We check out the entire

We check out the entire policy and also look for to integrate as well as offer result to all provisions so that none will certainly
be inoperative or meaningless.

Here is my web page ... motor trade insurance brokers (wiki.triplecollege.org)

If all your work is done on

If all your work is done on the road and also visiting your customers location,
then rod danger insurance coverage is the cover for
you.

Also visit my blog ... new cars coming out

So great deals of folks call

So great deals of folks call about looking for Insurance policy as well
as invest the entire discussion responding to concerns.

Visit my web-site; https://developer.jboss.org/people/guetirextlos1977

View Richard E. Dragon,

View Richard E. Dragon, Registered in R.I.: Car Permit Plates as well as the Registration of Motor used cars austin
in Rhode Island Since 1904, at mxi (1998).

I'm amazed, I have to admit.

I'm amazed, I have to admit. Rarely do I come across a blog that's equally educative and amusing, and without a doubt, you have hit the
nail on the head. The problem is something that not enough folks are speaking intelligently about.
Now i'm very happy that I came across this in my search for something
relating to this.

Tools created to support you

Tools created to support you get to a healthier weight and
reside a healthier way of life include things like Heart Price, Activity and Sleep Monitors.

Also visit my homepage; Bradley

I was wondering if you ever

I was wondering if you ever thought of changing
the layout of your site? Its very well written; I love
what youve got to say. But maybe you could a little more in the way
of content so people could connect with it better.
Youve got an awful lot of text for only having one
or two pictures. Maybe you could space it out better?

Motor field insurance policy

Motor field insurance policy under 25 has several added products that can be taken at the same time.

Here is my web blog ... http://raph.com/3dartists/members/viewProfile?uid=103262

Thus it is prudent to examine

Thus it is prudent to examine the crucial aspects and
adopt electric motor trade insurance companies trade insurance policy accordingly.

That likewise has one of the

That likewise has one of the most effective designed user interfaces of any type of video clip application on this checklist.

Here is my weblog - vacuum for car (Margot)

I have actually been surfing

I have actually been surfing online more than 2 hours today, yet I
never ever found any type of intriguing short article like yours.

Feel free to surf to my site - trade insurance singapore

If you desire to get a great

If you desire to get a great deal from this post
then you have to apply these techniques to your won blog.

Right here's exactly what it

Right here's exactly what it took to modification from a trade
job to a unassociated and also totally various task in a
workplace.

My blog post used cars dallas (http://dorothyscorner.com/dcccblog/?p=164)

This is a topic that's close

This is a topic that's close to my heart... Best wishes!
Where are your contact details though?

For auto manufacturers these

For auto manufacturers these could possibly be dropping sales, competitors
from abroad or Government policy changes over CARBON DIOXIDE emmissions.

Feel free to visit my website :: price of used cars

This is valuable advice for

This is valuable advice for e-mail email marketing best practices subject line
(http://www.purevolume.com/rooseveltatwi/posts/11211420/Anik+Singal+From+Weblog+Classroom+Interviews+Yaro+Starak+This+Thursday) and beyond.

Fascinating blog! Is your

Fascinating blog! Is your theme custom made or did you download it from somewhere?

A theme like yours with a few simple tweeks would really
make my blog shine. Please let me know where you got your design. Appreciate it

GDP = gross domestic product,

GDP = gross domestic product, lngdp_P = per head GDP in nominal United States dollars in log terms, mtgr = mortgage loan proportion.

I like the helpful

I like the helpful information you provide in your articles.
I will bookmark your blog and check again here frequently.
I'm quite certain I will learn plenty of new stuff right here!

Best of luck for the next!

Below, folks are adhering to

Below, folks are adhering to the design of buying as well as selling their
vehicles to Bristol Profession Center sellers.

Also visit my web page ... http://cheverst.co.uk/drive-royale-4-sport-mobility-scooter/

But, for those who sleep on a

But, for those who sleep on a plush, an extremely plush or a pillowtop mattress you NEED a pillowtop latex.

I was able to find good

I was able to find good information from your articles.

Pair your Sonos device along

Pair your Sonos device along with State of mind Mix, our
amazing new StreamingPlus songs solution made specifically for
small company.

Feel free to visit my website; best bag vacuum for
pet hair (Winifred)

In March 1994, Manitoba

In March 1994, Manitoba executed a no-fault system of automobile insurance
policy called the Car accident Defense Strategy (PIPP).

Here is my weblog - new cars under 20000 (Marko)

As a thanks for giving this

As a thanks for giving this handy feedback, we
lately began with a regular monthly testimonial
incentive program..

Also visit my page most powerful vacuum cleaner, Chanel,

Sometimes called a Silver's

Sometimes called a Silver's procedure, which is the simple removal
of the bunion bump on the toe joint.

Business could beverage

Business could beverage points up by bringing in debatable and
also new points of view.

Here is my web-site http://narutobox.com/?document_srl=82056

When someone writes an

When someone writes an article he/she maintains the image of a user in his/her brain that how a user can know it.
So that's why this post is outstdanding. Thanks!

I maske money online from

I maske money online from home no scams [http://mymilfmomma.tumblr.com] a living
full time on the net. I do lead generation for a variety
of companies and industry many distinct web sites.

To establish your Tones visit

To establish your Tones visit as well as comply with the associated with download the Beep
app, which are going to walk you until our simple setup method.

Look into my weblog: hoover windtunnel parts (Elvira)

They obtain expenditure

They obtain expenditure allowances agreed to by the subscription to compensate them for
the cost of acting on behalf of the Organization.

Look into my blog post used cars dallas

You likewise acquire the

You likewise acquire the choice to get a durable portable Q cart alongside any type of grill in the
Weber Q series.

Although Yahoo isn't the

Although Yahoo isn't the biggest, or the highest ranking search engine on the internet, it is still one
of the most essential, and if you want use search engine optimization and promotion as a main technique in your marketing arsenal, you unquestionably need to get
listed here. So what are you going to put in their search box is "website optimization tips".
While effective SEO needn't be difficult, it does take work.
Tests with a model like Page - Rank have shown that the system is
not infallible.

Also visit my site; http://www.Purevolume.com/listeners/haltingstem2057/posts/3243005/Custom+Business+Software+Development+Vs.+Boxed+Software

Field springs are

Field springs are occasionally break up into two smaller items for giant beds such as a queen and king-size mattress.

I always used to read

I always used to read paragraph in news papers but now as I am a user of web therefore from
now I am using net for posts, thanks to web.

UniCased Edge means

UniCased Edge means additional coils on the edge of the bed,
which is a better support, since you will not push the mattress sideways anymore.

Hozzászólás

A mező tartalma nem nyilvános.
  • Internal paths in double quotes, written as "internal:node/99", for example, are replaced with the appropriate absolute URL or relative path.
  • Engedélyezett HTML elemek: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <del> <img>
  • A webcímek és email címek automatikusan linkekké alakulnak.
  • A sorokat és bekezdéseket a rendszer automatikusan felismeri.
  • Engedélyezett HTML elemek: <a> <blockquote> <br> <cite> <code> <dd> <del> <div> <dl> <dt> <em> <li> <ol> <p> <span> <strong> <ul>
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <bash>, <c>, <cpp>, <drupal5>, <drupal6>, <java>, <javascript>, <mysql>, <php>, <python>, <ruby>, <sql>. The supported tag styles are: <foo>, [foo].
  • Minden email cím át lesz alakítva ember által olvasható módon, vagy (ha a JavaScript engedélyezett) ki lesz cserélve kattintható, de biztonságos hivatkozásra.