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

Hello, i feel that i saaw you

Hello, i feel that i saaw you visited my blog so i
came to return the want?.I am attempting to inn finding issues to improve my
web site!I suppose its good enough to make use oof some
of your ideas!!

Here is my site :: buku mimpi 3D

This meatloaf is sooo damp

This meatloaf is sooo damp and also tasty, I could not quit
consuming it. Absolutely one of tthe very best meatloafs I
have actually made.

Loook at my blog :: http://momsmeatloafrecipe.com (gapinghangover204.blog.com)

The partners consider

The partners consider Floo-id” (pronounced fluid) as their
top-edge device.

Feel free to surf to my page; repairing leaky toilet gasket (Juliana)

No es una agencia de viajes

No es una agencia de viajes ni vende nada, solo te redirige al distribuidor que te ofrece el mejor
plan. Tree House , situado en el Cobijo Nacional de Vida Silvestre Gandoca-Manzanillo de Para que no tengas excusas te he preparado una
lista con los vuelos más económicos que he encontrado desde diferentes
ciudades.

Feel free to visit my web page - hoteles en benidorm centro baratos

It’s truly a nice and

It’s truly a nice and beneficial piece of info. I’m glad that you just shared
this very helpful info with us. Please keep us up to
date. Thanks ipad 1 for sale sharing.

Nice to be visiting your blog

Nice to be visiting your blog once more. Nice this post.
Many thanks for sharing.

Feel free to surf to my web-site: ipad keyboard

Did you know that as much as

Did you know that as much as 80,000 gallons of water can be wasted each and every year
by an undetected fix leaky toilet gasket tank leak?

Constructing an identical set

Constructing an identical set of jewelry through a
number of presents demonstrates a commitment to the relationship between giver and receiver.

Visit my web site ... Brodie

Great weblog here!

Great weblog here! Additionally your web site loads up very fast!
What host are you the usage of? Can I get your affiliate
link to your host? I wish my web site loaded up
as fast as yours lol

Stop by my website probiotic america reviews

Great post. I was checking

Great post. I was checking constantly this weblog and I'm
inspired! Extremely helpful info particularly the final phase :) I maintain such information much.
I was looking for this particular info for a very long time.
Thank you and best of luck.

Also visit my blog post: probiotic america

This blog was... how do I say

This blog was... how do I say it? Relevant!! Finally I've found something that helped me.
Appreciate it!

My web site :: perfect biotics reviews

Hey! Do you know if they make

Hey! Do you know if they make any plugins to help with SEO?
I'm trying to get my blog to rank for some targeted keywords but I'm not seeing very good results.

If you know of any please share. Cheers!

Also visit my webpage: perfect biotics

You can choose any of the

You can choose any of the certifications according to your knowledge and skills.
The data fell into the hands of criminals 160 million credit cards.
You can also make use of Adobe logo anywhere on your website or
blogs and can also link with the community of ACE.

Hello to all, it's actually a

Hello to all, it's actually a good for me to go to see this web page, it contains useful Information.

Here is my page - perfect biotics

We are a gaggle of volunteers

We are a gaggle of volunteers and starting a brand new scheme in our community.
Your site offered us with useful info to work on. You've done a formidable task
and our whole community can be thankful to you.

my website - perfect biotics scam

Undoubtedly, the internet is

Undoubtedly, the internet is among the most preferred market places where sellers and buyers
meet. Driven aggressively, the cars will run out of power in about 30 minutes.
Go to the search tool and search for keyword like used cars in Bangalore, pre owned
cars and second hand cars in Bangalore.

Write more, thats all I have

Write more, thats all I have to say. Literally, it seems as though you relied on the video to make your point.
You obviously know what youre talking about, why
throw away your intelligence on just posting videos to your weblog when you
could be giving us something informative to read?

Also visit my web site ... probiotic america

It's going to be finish of

It's going to be finish of mine day, however before finish I am reading this fantastic post to improve my knowledge.

my page - probiotic america

Spelled in reverse it reveals

Spelled in reverse it reveals names Tobias Boon (the two main developers of MK, Ed
Boon and John Tobias). All game news on Examiner can be followed at the
Game On Facebook page and Twitter feed. Think about WHOM your subscribers are, what's their interests, hobbies, married, single, divorced, grandparents, newly weds
and now you're getting the message loud and clear.

Also visit my site :: mortal kombat it

I'm no longer positive the

I'm no longer positive the place you're gstting your information,however good topic.
I needs to spend a while learning much more or understanding more.
Thank you for wonderful info I was in search of this info for my mission.

After I initially left a

After I initially left a comment I appear to have clicked the -Notify me when new comments are added- checkbox and
now whenever a comment is added I get 4 emails with the exact same comment.
Perhaps there is an easy method you are able to remove me from that service?
Appreciate it!

Ahaa, its pleasant dialogue

Ahaa, its pleasant dialogue on the topic of this piece of writing at
this place at this website, I have read all that, so at
this time me also commenting here.

Hello! Someone in my Facebook

Hello! Someone in my Facebook group shared this site with us
so I came to look it over. I'm definitely enjoying the information. I'm book-marking and will be tweeting this
to my followers! Wonderful blog and superb style and design.

My web site; probiotic america reviews

I have been exploring for a

I have been exploring for a little for any high quality articles or weblog posts in this kind of house .
Exploring in Yahoo I ultimately stumbled upon this site. Reading this info So i'm satisfied to convey that I have a
very excellent uncanny feeling I discovered exactly what I needed.
I most surely will make certain to do not put out of your mind
this website and give it a look on a relentless
basis.

I’m usually to blogging and

I’m usually to blogging and site-building and i really admire
your content. The post has truly speaks my interest.

I am going to bookmark your site and keep checking for new information.

Review my weblog :: earthing

Usually I don't learn post on

Usually I don't learn post on blogs, but I would like to say that this write-up very forced me to check out
and do it! Your writing style has been surprised me. Thanks,
quite nice post.

Take a look at my page; perfect biotics scam

It isn't clinically

It isn't clinically confirmed, but that does
not make it any much less true, that it truly is the GREATEST Remedy a lady
may hope for: Pony Pain Administration (PPM).

my homepage ... lmg jewellery

I could not resist

I could not resist commenting. Well written!

Here is my web page - probiotic america

Hi there, I enjoy reading all

Hi there, I enjoy reading all of your article post. I like to
write a little comment to support you.

my homepage; perfect biotics

Jazz up a plain white shirt

Jazz up a plain white shirt with a handmade felt brooch.

Visit my web-site ... yoga jewellery

Appreciate this post. Let me

Appreciate this post. Let me try it out.

Feel free to surf to my blog post probiotic america reviews

Det mest populære binære

Det mest populære binære budet er et opp og ned bud som lar brukeren enten ”call”, noe
som betyr at aksjen vil stige eller ”put” som betyr at aksjeverdien vil synke.

My blog - drdorethasmith.com

Nice post. I learn some thing

Nice post. I learn some thing hard on distinct blogs everyday.
It will always be stimulating to read content of fantastic writers like you.

I’d choose to use some content in my small weblog in case you do
not mind. Of course I’ll provide a link on your own internet weblog.

Many thanks for sharing.

Also visit my site :: bowflex dumbbells

I visited several web pages

I visited several web pages except the audio quality for audio songs present at
this site is genuinely marvelous.

Look into my web blog - probiotic america reviews

Have you ever considered

Have you ever considered publishing an e-book or guest authoring
on other sites? I have a blog based upon on the same ideas you discuss and
would love to have you share some stories/information. I
know my audience would appreciate your work. If you are even remotely interested, feel free to send me an email.

Also visit my web page probiotic america

I always used to read

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

my web-site - perfect biotics scam

An interesting discussion is

An interesting discussion is definitely worth
comment. I believe that you should publish more about this subject, it may not be a taboo matter but typically folks don't discuss such issues.
To the next! Kind regards!!

Thanks for any other

Thanks for any other informative website. Where else may I gget that kind of info written in such aan ideal approach?
I have a challenge that I am just now operatying
on, and I've been at the glance out for such information.

This design is spectacular!

This design is spectacular! You most certainly know how to keep a reader entertained.
Between your wit and your videos, I was almost moved to start my own blog (well, almost...HaHa!) Excellent job.
I really loved what you had to say, and more than that, how you presented it.
Too cool!

Hi, I do believe this is a

Hi, I do believe this is a great site. I stumbledupon it ;)
I will revisit yet again since i have bookmarked it. Money and freedom is
the greatest way to change, may you be rich and continue to
help other people.

Feel free to surf to my website :: perfect biotics

Great content, I’m going to

Great content, I’m going to spend more time exploring
this subject.

Here is my web blog; bowflex selecttech 1090 adjustable dumbbell

I don't even know how I

I don't even know how I stopped up here, but I assumed this put up used to be great.
I don't recognize who you're however certainly you are going to a well-known blogger for those who are not already.

Cheers!

Bookmarked your wonderful

Bookmarked your wonderful website. Wonderful work, unique
way with words!

Look at my homepage premium cleanse reviews

You see, an appropriate

You see, an appropriate training session will actually weaken your muscles temporarily, and unless proper recovery and
regeneration are supplied they'll remain weaker, and then you works out again, further weakening parts of your muscles, and also the cycle continues.

Air Alert is a vertical jump program produced by TMT
sports in 1991. Another great example will be a volleyball player to be able to
jump high enough to slam the ball within the net.

Membantu mengecilkan

Membantu mengecilkan pori-pori, menghaluskan serta mencerahkan kulit wajah secara alami.

Look at my site ... otisjamesnashville.tumblr.com (Elizbeth)

Many people will benefit from

Many people will benefit from your writing. Cheers!

Here is my web page; grounding shoes

This is my first time visit

This is my first time visit at here and i am truly happy to read all at single place.

Hello to all, it's actually a

Hello to all, it's actually a nice for me to
visit this web page, it consists of priceless Information.

Check for moisture levels in

Check for moisture levels in the wood of your home or apartment.

RV Carports Direct is one of the largest distributors of quality
steel buildings, RV Covers and carports and metal garages in the continental United States.
Choosing an electric motor powerful enough to sustain the load of one's garage door is
completely pertinent.

Another major difference

Another major difference between the two is that while PPC is a paid form of advertising, organic search engine optimization is
absolutely free. Any business to conduct business on the web should have a web site
created especially homes for sale frederick md creating an awareness of their
products and ser-vices to the planet at large. Thematic relevance is of key importance for the creation of quality backlinks.
This mode of advertisement was faster than the earlier ones
and reached more people but it had its own limitations.

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.